LoopVectorize.cpp 403 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725
  1. //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
  10. // and generates target-independent LLVM-IR.
  11. // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
  12. // of instructions in order to estimate the profitability of vectorization.
  13. //
  14. // The loop vectorizer combines consecutive loop iterations into a single
  15. // 'wide' iteration. After this transformation the index is incremented
  16. // by the SIMD vector width, and not by one.
  17. //
  18. // This pass has three parts:
  19. // 1. The main loop pass that drives the different parts.
  20. // 2. LoopVectorizationLegality - A unit that checks for the legality
  21. // of the vectorization.
  22. // 3. InnerLoopVectorizer - A unit that performs the actual
  23. // widening of instructions.
  24. // 4. LoopVectorizationCostModel - A unit that checks for the profitability
  25. // of vectorization. It decides on the optimal vector width, which
  26. // can be one, if vectorization is not profitable.
  27. //
  28. // There is a development effort going on to migrate loop vectorizer to the
  29. // VPlan infrastructure and to introduce outer loop vectorization support (see
  30. // docs/Proposal/VectorizationPlan.rst and
  31. // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
  32. // purpose, we temporarily introduced the VPlan-native vectorization path: an
  33. // alternative vectorization path that is natively implemented on top of the
  34. // VPlan infrastructure. See EnableVPlanNativePath for enabling.
  35. //
  36. //===----------------------------------------------------------------------===//
  37. //
  38. // The reduction-variable vectorization is based on the paper:
  39. // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
  40. //
  41. // Variable uniformity checks are inspired by:
  42. // Karrenberg, R. and Hack, S. Whole Function Vectorization.
  43. //
  44. // The interleaved access vectorization is based on the paper:
  45. // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
  46. // Data for SIMD
  47. //
  48. // Other ideas/concepts are from:
  49. // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
  50. //
  51. // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
  52. // Vectorizing Compilers.
  53. //
  54. //===----------------------------------------------------------------------===//
  55. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  56. #include "LoopVectorizationPlanner.h"
  57. #include "VPRecipeBuilder.h"
  58. #include "VPlan.h"
  59. #include "VPlanHCFGBuilder.h"
  60. #include "VPlanPredicator.h"
  61. #include "VPlanTransforms.h"
  62. #include "llvm/ADT/APInt.h"
  63. #include "llvm/ADT/ArrayRef.h"
  64. #include "llvm/ADT/DenseMap.h"
  65. #include "llvm/ADT/DenseMapInfo.h"
  66. #include "llvm/ADT/Hashing.h"
  67. #include "llvm/ADT/MapVector.h"
  68. #include "llvm/ADT/None.h"
  69. #include "llvm/ADT/Optional.h"
  70. #include "llvm/ADT/STLExtras.h"
  71. #include "llvm/ADT/SetVector.h"
  72. #include "llvm/ADT/SmallPtrSet.h"
  73. #include "llvm/ADT/SmallVector.h"
  74. #include "llvm/ADT/Statistic.h"
  75. #include "llvm/ADT/StringRef.h"
  76. #include "llvm/ADT/Twine.h"
  77. #include "llvm/ADT/iterator_range.h"
  78. #include "llvm/Analysis/AssumptionCache.h"
  79. #include "llvm/Analysis/BasicAliasAnalysis.h"
  80. #include "llvm/Analysis/BlockFrequencyInfo.h"
  81. #include "llvm/Analysis/CFG.h"
  82. #include "llvm/Analysis/CodeMetrics.h"
  83. #include "llvm/Analysis/DemandedBits.h"
  84. #include "llvm/Analysis/GlobalsModRef.h"
  85. #include "llvm/Analysis/LoopAccessAnalysis.h"
  86. #include "llvm/Analysis/LoopAnalysisManager.h"
  87. #include "llvm/Analysis/LoopInfo.h"
  88. #include "llvm/Analysis/LoopIterator.h"
  89. #include "llvm/Analysis/MemorySSA.h"
  90. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  91. #include "llvm/Analysis/ProfileSummaryInfo.h"
  92. #include "llvm/Analysis/ScalarEvolution.h"
  93. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  94. #include "llvm/Analysis/TargetLibraryInfo.h"
  95. #include "llvm/Analysis/TargetTransformInfo.h"
  96. #include "llvm/Analysis/VectorUtils.h"
  97. #include "llvm/IR/Attributes.h"
  98. #include "llvm/IR/BasicBlock.h"
  99. #include "llvm/IR/CFG.h"
  100. #include "llvm/IR/Constant.h"
  101. #include "llvm/IR/Constants.h"
  102. #include "llvm/IR/DataLayout.h"
  103. #include "llvm/IR/DebugInfoMetadata.h"
  104. #include "llvm/IR/DebugLoc.h"
  105. #include "llvm/IR/DerivedTypes.h"
  106. #include "llvm/IR/DiagnosticInfo.h"
  107. #include "llvm/IR/Dominators.h"
  108. #include "llvm/IR/Function.h"
  109. #include "llvm/IR/IRBuilder.h"
  110. #include "llvm/IR/InstrTypes.h"
  111. #include "llvm/IR/Instruction.h"
  112. #include "llvm/IR/Instructions.h"
  113. #include "llvm/IR/IntrinsicInst.h"
  114. #include "llvm/IR/Intrinsics.h"
  115. #include "llvm/IR/LLVMContext.h"
  116. #include "llvm/IR/Metadata.h"
  117. #include "llvm/IR/Module.h"
  118. #include "llvm/IR/Operator.h"
  119. #include "llvm/IR/Type.h"
  120. #include "llvm/IR/Use.h"
  121. #include "llvm/IR/User.h"
  122. #include "llvm/IR/Value.h"
  123. #include "llvm/IR/ValueHandle.h"
  124. #include "llvm/IR/Verifier.h"
  125. #include "llvm/InitializePasses.h"
  126. #include "llvm/Pass.h"
  127. #include "llvm/Support/Casting.h"
  128. #include "llvm/Support/CommandLine.h"
  129. #include "llvm/Support/Compiler.h"
  130. #include "llvm/Support/Debug.h"
  131. #include "llvm/Support/ErrorHandling.h"
  132. #include "llvm/Support/InstructionCost.h"
  133. #include "llvm/Support/MathExtras.h"
  134. #include "llvm/Support/raw_ostream.h"
  135. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  136. #include "llvm/Transforms/Utils/InjectTLIMappings.h"
  137. #include "llvm/Transforms/Utils/LoopSimplify.h"
  138. #include "llvm/Transforms/Utils/LoopUtils.h"
  139. #include "llvm/Transforms/Utils/LoopVersioning.h"
  140. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  141. #include "llvm/Transforms/Utils/SizeOpts.h"
  142. #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
  143. #include <algorithm>
  144. #include <cassert>
  145. #include <cstdint>
  146. #include <cstdlib>
  147. #include <functional>
  148. #include <iterator>
  149. #include <limits>
  150. #include <memory>
  151. #include <string>
  152. #include <tuple>
  153. #include <utility>
  154. using namespace llvm;
  155. #define LV_NAME "loop-vectorize"
  156. #define DEBUG_TYPE LV_NAME
  157. #ifndef NDEBUG
  158. const char VerboseDebug[] = DEBUG_TYPE "-verbose";
  159. #endif
  160. /// @{
  161. /// Metadata attribute names
  162. const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
  163. const char LLVMLoopVectorizeFollowupVectorized[] =
  164. "llvm.loop.vectorize.followup_vectorized";
  165. const char LLVMLoopVectorizeFollowupEpilogue[] =
  166. "llvm.loop.vectorize.followup_epilogue";
  167. /// @}
  168. STATISTIC(LoopsVectorized, "Number of loops vectorized");
  169. STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
  170. STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
  171. static cl::opt<bool> EnableEpilogueVectorization(
  172. "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
  173. cl::desc("Enable vectorization of epilogue loops."));
  174. static cl::opt<unsigned> EpilogueVectorizationForceVF(
  175. "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
  176. cl::desc("When epilogue vectorization is enabled, and a value greater than "
  177. "1 is specified, forces the given VF for all applicable epilogue "
  178. "loops."));
  179. static cl::opt<unsigned> EpilogueVectorizationMinVF(
  180. "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
  181. cl::desc("Only loops with vectorization factor equal to or larger than "
  182. "the specified value are considered for epilogue vectorization."));
  183. /// Loops with a known constant trip count below this number are vectorized only
  184. /// if no scalar iteration overheads are incurred.
  185. static cl::opt<unsigned> TinyTripCountVectorThreshold(
  186. "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
  187. cl::desc("Loops with a constant trip count that is smaller than this "
  188. "value are vectorized only if no scalar iteration overheads "
  189. "are incurred."));
  190. // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
  191. // that predication is preferred, and this lists all options. I.e., the
  192. // vectorizer will try to fold the tail-loop (epilogue) into the vector body
  193. // and predicate the instructions accordingly. If tail-folding fails, there are
  194. // different fallback strategies depending on these values:
  195. namespace PreferPredicateTy {
  196. enum Option {
  197. ScalarEpilogue = 0,
  198. PredicateElseScalarEpilogue,
  199. PredicateOrDontVectorize
  200. };
  201. } // namespace PreferPredicateTy
  202. static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
  203. "prefer-predicate-over-epilogue",
  204. cl::init(PreferPredicateTy::ScalarEpilogue),
  205. cl::Hidden,
  206. cl::desc("Tail-folding and predication preferences over creating a scalar "
  207. "epilogue loop."),
  208. cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
  209. "scalar-epilogue",
  210. "Don't tail-predicate loops, create scalar epilogue"),
  211. clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
  212. "predicate-else-scalar-epilogue",
  213. "prefer tail-folding, create scalar epilogue if tail "
  214. "folding fails."),
  215. clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
  216. "predicate-dont-vectorize",
  217. "prefers tail-folding, don't attempt vectorization if "
  218. "tail-folding fails.")));
  219. static cl::opt<bool> MaximizeBandwidth(
  220. "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
  221. cl::desc("Maximize bandwidth when selecting vectorization factor which "
  222. "will be determined by the smallest type in loop."));
  223. static cl::opt<bool> EnableInterleavedMemAccesses(
  224. "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  225. cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
  226. /// An interleave-group may need masking if it resides in a block that needs
  227. /// predication, or in order to mask away gaps.
  228. static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
  229. "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  230. cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
  231. static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
  232. "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
  233. cl::desc("We don't interleave loops with a estimated constant trip count "
  234. "below this number"));
  235. static cl::opt<unsigned> ForceTargetNumScalarRegs(
  236. "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
  237. cl::desc("A flag that overrides the target's number of scalar registers."));
  238. static cl::opt<unsigned> ForceTargetNumVectorRegs(
  239. "force-target-num-vector-regs", cl::init(0), cl::Hidden,
  240. cl::desc("A flag that overrides the target's number of vector registers."));
  241. static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
  242. "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
  243. cl::desc("A flag that overrides the target's max interleave factor for "
  244. "scalar loops."));
  245. static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
  246. "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
  247. cl::desc("A flag that overrides the target's max interleave factor for "
  248. "vectorized loops."));
  249. static cl::opt<unsigned> ForceTargetInstructionCost(
  250. "force-target-instruction-cost", cl::init(0), cl::Hidden,
  251. cl::desc("A flag that overrides the target's expected cost for "
  252. "an instruction to a single constant value. Mostly "
  253. "useful for getting consistent testing."));
  254. static cl::opt<bool> ForceTargetSupportsScalableVectors(
  255. "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
  256. cl::desc(
  257. "Pretend that scalable vectors are supported, even if the target does "
  258. "not support them. This flag should only be used for testing."));
  259. static cl::opt<unsigned> SmallLoopCost(
  260. "small-loop-cost", cl::init(20), cl::Hidden,
  261. cl::desc(
  262. "The cost of a loop that is considered 'small' by the interleaver."));
  263. static cl::opt<bool> LoopVectorizeWithBlockFrequency(
  264. "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
  265. cl::desc("Enable the use of the block frequency analysis to access PGO "
  266. "heuristics minimizing code growth in cold regions and being more "
  267. "aggressive in hot regions."));
  268. // Runtime interleave loops for load/store throughput.
  269. static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
  270. "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
  271. cl::desc(
  272. "Enable runtime interleaving until load/store ports are saturated"));
  273. /// Interleave small loops with scalar reductions.
  274. static cl::opt<bool> InterleaveSmallLoopScalarReduction(
  275. "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
  276. cl::desc("Enable interleaving for loops with small iteration counts that "
  277. "contain scalar reductions to expose ILP."));
  278. /// The number of stores in a loop that are allowed to need predication.
  279. static cl::opt<unsigned> NumberOfStoresToPredicate(
  280. "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
  281. cl::desc("Max number of stores to be predicated behind an if."));
  282. static cl::opt<bool> EnableIndVarRegisterHeur(
  283. "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
  284. cl::desc("Count the induction variable only once when interleaving"));
  285. static cl::opt<bool> EnableCondStoresVectorization(
  286. "enable-cond-stores-vec", cl::init(true), cl::Hidden,
  287. cl::desc("Enable if predication of stores during vectorization."));
  288. static cl::opt<unsigned> MaxNestedScalarReductionIC(
  289. "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
  290. cl::desc("The maximum interleave count to use when interleaving a scalar "
  291. "reduction in a nested loop."));
  292. static cl::opt<bool>
  293. PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
  294. cl::Hidden,
  295. cl::desc("Prefer in-loop vector reductions, "
  296. "overriding the targets preference."));
  297. static cl::opt<bool> PreferPredicatedReductionSelect(
  298. "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
  299. cl::desc(
  300. "Prefer predicating a reduction operation over an after loop select."));
  301. cl::opt<bool> EnableVPlanNativePath(
  302. "enable-vplan-native-path", cl::init(false), cl::Hidden,
  303. cl::desc("Enable VPlan-native vectorization path with "
  304. "support for outer loop vectorization."));
  305. // FIXME: Remove this switch once we have divergence analysis. Currently we
  306. // assume divergent non-backedge branches when this switch is true.
  307. cl::opt<bool> EnableVPlanPredication(
  308. "enable-vplan-predication", cl::init(false), cl::Hidden,
  309. cl::desc("Enable VPlan-native vectorization path predicator with "
  310. "support for outer loop vectorization."));
  311. // This flag enables the stress testing of the VPlan H-CFG construction in the
  312. // VPlan-native vectorization path. It must be used in conjuction with
  313. // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
  314. // verification of the H-CFGs built.
  315. static cl::opt<bool> VPlanBuildStressTest(
  316. "vplan-build-stress-test", cl::init(false), cl::Hidden,
  317. cl::desc(
  318. "Build VPlan for every supported loop nest in the function and bail "
  319. "out right after the build (stress test the VPlan H-CFG construction "
  320. "in the VPlan-native vectorization path)."));
  321. cl::opt<bool> llvm::EnableLoopInterleaving(
  322. "interleave-loops", cl::init(true), cl::Hidden,
  323. cl::desc("Enable loop interleaving in Loop vectorization passes"));
  324. cl::opt<bool> llvm::EnableLoopVectorization(
  325. "vectorize-loops", cl::init(true), cl::Hidden,
  326. cl::desc("Run the Loop vectorization passes"));
  327. /// A helper function that returns the type of loaded or stored value.
  328. static Type *getMemInstValueType(Value *I) {
  329. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  330. "Expected Load or Store instruction");
  331. if (auto *LI = dyn_cast<LoadInst>(I))
  332. return LI->getType();
  333. return cast<StoreInst>(I)->getValueOperand()->getType();
  334. }
  335. /// A helper function that returns true if the given type is irregular. The
  336. /// type is irregular if its allocated size doesn't equal the store size of an
  337. /// element of the corresponding vector type.
  338. static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
  339. // Determine if an array of N elements of type Ty is "bitcast compatible"
  340. // with a <N x Ty> vector.
  341. // This is only true if there is no padding between the array elements.
  342. return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
  343. }
  344. /// A helper function that returns the reciprocal of the block probability of
  345. /// predicated blocks. If we return X, we are assuming the predicated block
  346. /// will execute once for every X iterations of the loop header.
  347. ///
  348. /// TODO: We should use actual block probability here, if available. Currently,
  349. /// we always assume predicated blocks have a 50% chance of executing.
  350. static unsigned getReciprocalPredBlockProb() { return 2; }
  351. /// A helper function that adds a 'fast' flag to floating-point operations.
  352. static Value *addFastMathFlag(Value *V) {
  353. if (isa<FPMathOperator>(V))
  354. cast<Instruction>(V)->setFastMathFlags(FastMathFlags::getFast());
  355. return V;
  356. }
  357. static Value *addFastMathFlag(Value *V, FastMathFlags FMF) {
  358. if (isa<FPMathOperator>(V))
  359. cast<Instruction>(V)->setFastMathFlags(FMF);
  360. return V;
  361. }
  362. /// A helper function that returns an integer or floating-point constant with
  363. /// value C.
  364. static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
  365. return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
  366. : ConstantFP::get(Ty, C);
  367. }
  368. /// Returns "best known" trip count for the specified loop \p L as defined by
  369. /// the following procedure:
  370. /// 1) Returns exact trip count if it is known.
  371. /// 2) Returns expected trip count according to profile data if any.
  372. /// 3) Returns upper bound estimate if it is known.
  373. /// 4) Returns None if all of the above failed.
  374. static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
  375. // Check if exact trip count is known.
  376. if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
  377. return ExpectedTC;
  378. // Check if there is an expected trip count available from profile data.
  379. if (LoopVectorizeWithBlockFrequency)
  380. if (auto EstimatedTC = getLoopEstimatedTripCount(L))
  381. return EstimatedTC;
  382. // Check if upper bound estimate is known.
  383. if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
  384. return ExpectedTC;
  385. return None;
  386. }
  387. namespace llvm {
  388. /// InnerLoopVectorizer vectorizes loops which contain only one basic
  389. /// block to a specified vectorization factor (VF).
  390. /// This class performs the widening of scalars into vectors, or multiple
  391. /// scalars. This class also implements the following features:
  392. /// * It inserts an epilogue loop for handling loops that don't have iteration
  393. /// counts that are known to be a multiple of the vectorization factor.
  394. /// * It handles the code generation for reduction variables.
  395. /// * Scalarization (implementation using scalars) of un-vectorizable
  396. /// instructions.
  397. /// InnerLoopVectorizer does not perform any vectorization-legality
  398. /// checks, and relies on the caller to check for the different legality
  399. /// aspects. The InnerLoopVectorizer relies on the
  400. /// LoopVectorizationLegality class to provide information about the induction
  401. /// and reduction variables that were found to a given vectorization factor.
  402. class InnerLoopVectorizer {
  403. public:
  404. InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  405. LoopInfo *LI, DominatorTree *DT,
  406. const TargetLibraryInfo *TLI,
  407. const TargetTransformInfo *TTI, AssumptionCache *AC,
  408. OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
  409. unsigned UnrollFactor, LoopVectorizationLegality *LVL,
  410. LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
  411. ProfileSummaryInfo *PSI)
  412. : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
  413. AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
  414. Builder(PSE.getSE()->getContext()),
  415. VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM),
  416. BFI(BFI), PSI(PSI) {
  417. // Query this against the original loop and save it here because the profile
  418. // of the original loop header may change as the transformation happens.
  419. OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
  420. OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
  421. }
  422. virtual ~InnerLoopVectorizer() = default;
  423. /// Create a new empty loop that will contain vectorized instructions later
  424. /// on, while the old loop will be used as the scalar remainder. Control flow
  425. /// is generated around the vectorized (and scalar epilogue) loops consisting
  426. /// of various checks and bypasses. Return the pre-header block of the new
  427. /// loop.
  428. /// In the case of epilogue vectorization, this function is overriden to
  429. /// handle the more complex control flow around the loops.
  430. virtual BasicBlock *createVectorizedLoopSkeleton();
  431. /// Widen a single instruction within the innermost loop.
  432. void widenInstruction(Instruction &I, VPValue *Def, VPUser &Operands,
  433. VPTransformState &State);
  434. /// Widen a single call instruction within the innermost loop.
  435. void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
  436. VPTransformState &State);
  437. /// Widen a single select instruction within the innermost loop.
  438. void widenSelectInstruction(SelectInst &I, VPValue *VPDef, VPUser &Operands,
  439. bool InvariantCond, VPTransformState &State);
  440. /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
  441. void fixVectorizedLoop();
  442. // Return true if any runtime check is added.
  443. bool areSafetyChecksAdded() { return AddedSafetyChecks; }
  444. /// A type for vectorized values in the new loop. Each value from the
  445. /// original loop, when vectorized, is represented by UF vector values in the
  446. /// new unrolled loop, where UF is the unroll factor.
  447. using VectorParts = SmallVector<Value *, 2>;
  448. /// Vectorize a single GetElementPtrInst based on information gathered and
  449. /// decisions taken during planning.
  450. void widenGEP(GetElementPtrInst *GEP, VPValue *VPDef, VPUser &Indices,
  451. unsigned UF, ElementCount VF, bool IsPtrLoopInvariant,
  452. SmallBitVector &IsIndexLoopInvariant, VPTransformState &State);
  453. /// Vectorize a single PHINode in a block. This method handles the induction
  454. /// variable canonicalization. It supports both VF = 1 for unrolled loops and
  455. /// arbitrary length vectors.
  456. void widenPHIInstruction(Instruction *PN, RecurrenceDescriptor *RdxDesc,
  457. Value *StartV, unsigned UF, ElementCount VF);
  458. /// A helper function to scalarize a single Instruction in the innermost loop.
  459. /// Generates a sequence of scalar instances for each lane between \p MinLane
  460. /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
  461. /// inclusive. Uses the VPValue operands from \p Operands instead of \p
  462. /// Instr's operands.
  463. void scalarizeInstruction(Instruction *Instr, VPUser &Operands,
  464. const VPIteration &Instance, bool IfPredicateInstr,
  465. VPTransformState &State);
  466. /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
  467. /// is provided, the integer induction variable will first be truncated to
  468. /// the corresponding type.
  469. void widenIntOrFpInduction(PHINode *IV, Value *Start,
  470. TruncInst *Trunc = nullptr);
  471. /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
  472. /// vector or scalar value on-demand if one is not yet available. When
  473. /// vectorizing a loop, we visit the definition of an instruction before its
  474. /// uses. When visiting the definition, we either vectorize or scalarize the
  475. /// instruction, creating an entry for it in the corresponding map. (In some
  476. /// cases, such as induction variables, we will create both vector and scalar
  477. /// entries.) Then, as we encounter uses of the definition, we derive values
  478. /// for each scalar or vector use unless such a value is already available.
  479. /// For example, if we scalarize a definition and one of its uses is vector,
  480. /// we build the required vector on-demand with an insertelement sequence
  481. /// when visiting the use. Otherwise, if the use is scalar, we can use the
  482. /// existing scalar definition.
  483. ///
  484. /// Return a value in the new loop corresponding to \p V from the original
  485. /// loop at unroll index \p Part. If the value has already been vectorized,
  486. /// the corresponding vector entry in VectorLoopValueMap is returned. If,
  487. /// however, the value has a scalar entry in VectorLoopValueMap, we construct
  488. /// a new vector value on-demand by inserting the scalar values into a vector
  489. /// with an insertelement sequence. If the value has been neither vectorized
  490. /// nor scalarized, it must be loop invariant, so we simply broadcast the
  491. /// value into a vector.
  492. Value *getOrCreateVectorValue(Value *V, unsigned Part);
  493. void setVectorValue(Value *Scalar, unsigned Part, Value *Vector) {
  494. VectorLoopValueMap.setVectorValue(Scalar, Part, Vector);
  495. }
  496. /// Return a value in the new loop corresponding to \p V from the original
  497. /// loop at unroll and vector indices \p Instance. If the value has been
  498. /// vectorized but not scalarized, the necessary extractelement instruction
  499. /// will be generated.
  500. Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
  501. /// Construct the vector value of a scalarized value \p V one lane at a time.
  502. void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
  503. /// Try to vectorize interleaved access group \p Group with the base address
  504. /// given in \p Addr, optionally masking the vector operations if \p
  505. /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
  506. /// values in the vectorized loop.
  507. void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
  508. ArrayRef<VPValue *> VPDefs,
  509. VPTransformState &State, VPValue *Addr,
  510. ArrayRef<VPValue *> StoredValues,
  511. VPValue *BlockInMask = nullptr);
  512. /// Vectorize Load and Store instructions with the base address given in \p
  513. /// Addr, optionally masking the vector operations if \p BlockInMask is
  514. /// non-null. Use \p State to translate given VPValues to IR values in the
  515. /// vectorized loop.
  516. void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
  517. VPValue *Def, VPValue *Addr,
  518. VPValue *StoredValue, VPValue *BlockInMask);
  519. /// Set the debug location in the builder using the debug location in
  520. /// the instruction.
  521. void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
  522. /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
  523. void fixNonInductionPHIs(void);
  524. protected:
  525. friend class LoopVectorizationPlanner;
  526. /// A small list of PHINodes.
  527. using PhiVector = SmallVector<PHINode *, 4>;
  528. /// A type for scalarized values in the new loop. Each value from the
  529. /// original loop, when scalarized, is represented by UF x VF scalar values
  530. /// in the new unrolled loop, where UF is the unroll factor and VF is the
  531. /// vectorization factor.
  532. using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
  533. /// Set up the values of the IVs correctly when exiting the vector loop.
  534. void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
  535. Value *CountRoundDown, Value *EndValue,
  536. BasicBlock *MiddleBlock);
  537. /// Create a new induction variable inside L.
  538. PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
  539. Value *Step, Instruction *DL);
  540. /// Handle all cross-iteration phis in the header.
  541. void fixCrossIterationPHIs();
  542. /// Fix a first-order recurrence. This is the second phase of vectorizing
  543. /// this phi node.
  544. void fixFirstOrderRecurrence(PHINode *Phi);
  545. /// Fix a reduction cross-iteration phi. This is the second phase of
  546. /// vectorizing this phi node.
  547. void fixReduction(PHINode *Phi);
  548. /// Clear NSW/NUW flags from reduction instructions if necessary.
  549. void clearReductionWrapFlags(RecurrenceDescriptor &RdxDesc);
  550. /// Fixup the LCSSA phi nodes in the unique exit block. This simply
  551. /// means we need to add the appropriate incoming value from the middle
  552. /// block as exiting edges from the scalar epilogue loop (if present) are
  553. /// already in place, and we exit the vector loop exclusively to the middle
  554. /// block.
  555. void fixLCSSAPHIs();
  556. /// Iteratively sink the scalarized operands of a predicated instruction into
  557. /// the block that was created for it.
  558. void sinkScalarOperands(Instruction *PredInst);
  559. /// Shrinks vector element sizes to the smallest bitwidth they can be legally
  560. /// represented as.
  561. void truncateToMinimalBitwidths();
  562. /// Create a broadcast instruction. This method generates a broadcast
  563. /// instruction (shuffle) for loop invariant values and for the induction
  564. /// value. If this is the induction variable then we extend it to N, N+1, ...
  565. /// this is needed because each iteration in the loop corresponds to a SIMD
  566. /// element.
  567. virtual Value *getBroadcastInstrs(Value *V);
  568. /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
  569. /// to each vector element of Val. The sequence starts at StartIndex.
  570. /// \p Opcode is relevant for FP induction variable.
  571. virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
  572. Instruction::BinaryOps Opcode =
  573. Instruction::BinaryOpsEnd);
  574. /// Compute scalar induction steps. \p ScalarIV is the scalar induction
  575. /// variable on which to base the steps, \p Step is the size of the step, and
  576. /// \p EntryVal is the value from the original loop that maps to the steps.
  577. /// Note that \p EntryVal doesn't have to be an induction variable - it
  578. /// can also be a truncate instruction.
  579. void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
  580. const InductionDescriptor &ID);
  581. /// Create a vector induction phi node based on an existing scalar one. \p
  582. /// EntryVal is the value from the original loop that maps to the vector phi
  583. /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
  584. /// truncate instruction, instead of widening the original IV, we widen a
  585. /// version of the IV truncated to \p EntryVal's type.
  586. void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
  587. Value *Step, Value *Start,
  588. Instruction *EntryVal);
  589. /// Returns true if an instruction \p I should be scalarized instead of
  590. /// vectorized for the chosen vectorization factor.
  591. bool shouldScalarizeInstruction(Instruction *I) const;
  592. /// Returns true if we should generate a scalar version of \p IV.
  593. bool needsScalarInduction(Instruction *IV) const;
  594. /// If there is a cast involved in the induction variable \p ID, which should
  595. /// be ignored in the vectorized loop body, this function records the
  596. /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
  597. /// cast. We had already proved that the casted Phi is equal to the uncasted
  598. /// Phi in the vectorized loop (under a runtime guard), and therefore
  599. /// there is no need to vectorize the cast - the same value can be used in the
  600. /// vector loop for both the Phi and the cast.
  601. /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
  602. /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
  603. ///
  604. /// \p EntryVal is the value from the original loop that maps to the vector
  605. /// phi node and is used to distinguish what is the IV currently being
  606. /// processed - original one (if \p EntryVal is a phi corresponding to the
  607. /// original IV) or the "newly-created" one based on the proof mentioned above
  608. /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
  609. /// latter case \p EntryVal is a TruncInst and we must not record anything for
  610. /// that IV, but it's error-prone to expect callers of this routine to care
  611. /// about that, hence this explicit parameter.
  612. void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID,
  613. const Instruction *EntryVal,
  614. Value *VectorLoopValue,
  615. unsigned Part,
  616. unsigned Lane = UINT_MAX);
  617. /// Generate a shuffle sequence that will reverse the vector Vec.
  618. virtual Value *reverseVector(Value *Vec);
  619. /// Returns (and creates if needed) the original loop trip count.
  620. Value *getOrCreateTripCount(Loop *NewLoop);
  621. /// Returns (and creates if needed) the trip count of the widened loop.
  622. Value *getOrCreateVectorTripCount(Loop *NewLoop);
  623. /// Returns a bitcasted value to the requested vector type.
  624. /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
  625. Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
  626. const DataLayout &DL);
  627. /// Emit a bypass check to see if the vector trip count is zero, including if
  628. /// it overflows.
  629. void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
  630. /// Emit a bypass check to see if all of the SCEV assumptions we've
  631. /// had to make are correct.
  632. void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
  633. /// Emit bypass checks to check any memory assumptions we may have made.
  634. void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
  635. /// Compute the transformed value of Index at offset StartValue using step
  636. /// StepValue.
  637. /// For integer induction, returns StartValue + Index * StepValue.
  638. /// For pointer induction, returns StartValue[Index * StepValue].
  639. /// FIXME: The newly created binary instructions should contain nsw/nuw
  640. /// flags, which can be found from the original scalar operations.
  641. Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
  642. const DataLayout &DL,
  643. const InductionDescriptor &ID) const;
  644. /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
  645. /// vector loop preheader, middle block and scalar preheader. Also
  646. /// allocate a loop object for the new vector loop and return it.
  647. Loop *createVectorLoopSkeleton(StringRef Prefix);
  648. /// Create new phi nodes for the induction variables to resume iteration count
  649. /// in the scalar epilogue, from where the vectorized loop left off (given by
  650. /// \p VectorTripCount).
  651. /// In cases where the loop skeleton is more complicated (eg. epilogue
  652. /// vectorization) and the resume values can come from an additional bypass
  653. /// block, the \p AdditionalBypass pair provides information about the bypass
  654. /// block and the end value on the edge from bypass to this loop.
  655. void createInductionResumeValues(
  656. Loop *L, Value *VectorTripCount,
  657. std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
  658. /// Complete the loop skeleton by adding debug MDs, creating appropriate
  659. /// conditional branches in the middle block, preparing the builder and
  660. /// running the verifier. Take in the vector loop \p L as argument, and return
  661. /// the preheader of the completed vector loop.
  662. BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
  663. /// Add additional metadata to \p To that was not present on \p Orig.
  664. ///
  665. /// Currently this is used to add the noalias annotations based on the
  666. /// inserted memchecks. Use this for instructions that are *cloned* into the
  667. /// vector loop.
  668. void addNewMetadata(Instruction *To, const Instruction *Orig);
  669. /// Add metadata from one instruction to another.
  670. ///
  671. /// This includes both the original MDs from \p From and additional ones (\see
  672. /// addNewMetadata). Use this for *newly created* instructions in the vector
  673. /// loop.
  674. void addMetadata(Instruction *To, Instruction *From);
  675. /// Similar to the previous function but it adds the metadata to a
  676. /// vector of instructions.
  677. void addMetadata(ArrayRef<Value *> To, Instruction *From);
  678. /// Allow subclasses to override and print debug traces before/after vplan
  679. /// execution, when trace information is requested.
  680. virtual void printDebugTracesAtStart(){};
  681. virtual void printDebugTracesAtEnd(){};
  682. /// The original loop.
  683. Loop *OrigLoop;
  684. /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
  685. /// dynamic knowledge to simplify SCEV expressions and converts them to a
  686. /// more usable form.
  687. PredicatedScalarEvolution &PSE;
  688. /// Loop Info.
  689. LoopInfo *LI;
  690. /// Dominator Tree.
  691. DominatorTree *DT;
  692. /// Alias Analysis.
  693. AAResults *AA;
  694. /// Target Library Info.
  695. const TargetLibraryInfo *TLI;
  696. /// Target Transform Info.
  697. const TargetTransformInfo *TTI;
  698. /// Assumption Cache.
  699. AssumptionCache *AC;
  700. /// Interface to emit optimization remarks.
  701. OptimizationRemarkEmitter *ORE;
  702. /// LoopVersioning. It's only set up (non-null) if memchecks were
  703. /// used.
  704. ///
  705. /// This is currently only used to add no-alias metadata based on the
  706. /// memchecks. The actually versioning is performed manually.
  707. std::unique_ptr<LoopVersioning> LVer;
  708. /// The vectorization SIMD factor to use. Each vector will have this many
  709. /// vector elements.
  710. ElementCount VF;
  711. /// The vectorization unroll factor to use. Each scalar is vectorized to this
  712. /// many different vector instructions.
  713. unsigned UF;
  714. /// The builder that we use
  715. IRBuilder<> Builder;
  716. // --- Vectorization state ---
  717. /// The vector-loop preheader.
  718. BasicBlock *LoopVectorPreHeader;
  719. /// The scalar-loop preheader.
  720. BasicBlock *LoopScalarPreHeader;
  721. /// Middle Block between the vector and the scalar.
  722. BasicBlock *LoopMiddleBlock;
  723. /// The (unique) ExitBlock of the scalar loop. Note that
  724. /// there can be multiple exiting edges reaching this block.
  725. BasicBlock *LoopExitBlock;
  726. /// The vector loop body.
  727. BasicBlock *LoopVectorBody;
  728. /// The scalar loop body.
  729. BasicBlock *LoopScalarBody;
  730. /// A list of all bypass blocks. The first block is the entry of the loop.
  731. SmallVector<BasicBlock *, 4> LoopBypassBlocks;
  732. /// The new Induction variable which was added to the new block.
  733. PHINode *Induction = nullptr;
  734. /// The induction variable of the old basic block.
  735. PHINode *OldInduction = nullptr;
  736. /// Maps values from the original loop to their corresponding values in the
  737. /// vectorized loop. A key value can map to either vector values, scalar
  738. /// values or both kinds of values, depending on whether the key was
  739. /// vectorized and scalarized.
  740. VectorizerValueMap VectorLoopValueMap;
  741. /// Store instructions that were predicated.
  742. SmallVector<Instruction *, 4> PredicatedInstructions;
  743. /// Trip count of the original loop.
  744. Value *TripCount = nullptr;
  745. /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
  746. Value *VectorTripCount = nullptr;
  747. /// The legality analysis.
  748. LoopVectorizationLegality *Legal;
  749. /// The profitablity analysis.
  750. LoopVectorizationCostModel *Cost;
  751. // Record whether runtime checks are added.
  752. bool AddedSafetyChecks = false;
  753. // Holds the end values for each induction variable. We save the end values
  754. // so we can later fix-up the external users of the induction variables.
  755. DenseMap<PHINode *, Value *> IVEndValues;
  756. // Vector of original scalar PHIs whose corresponding widened PHIs need to be
  757. // fixed up at the end of vector code generation.
  758. SmallVector<PHINode *, 8> OrigPHIsToFix;
  759. /// BFI and PSI are used to check for profile guided size optimizations.
  760. BlockFrequencyInfo *BFI;
  761. ProfileSummaryInfo *PSI;
  762. // Whether this loop should be optimized for size based on profile guided size
  763. // optimizatios.
  764. bool OptForSizeBasedOnProfile;
  765. };
  766. class InnerLoopUnroller : public InnerLoopVectorizer {
  767. public:
  768. InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  769. LoopInfo *LI, DominatorTree *DT,
  770. const TargetLibraryInfo *TLI,
  771. const TargetTransformInfo *TTI, AssumptionCache *AC,
  772. OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
  773. LoopVectorizationLegality *LVL,
  774. LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
  775. ProfileSummaryInfo *PSI)
  776. : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
  777. ElementCount::getFixed(1), UnrollFactor, LVL, CM,
  778. BFI, PSI) {}
  779. private:
  780. Value *getBroadcastInstrs(Value *V) override;
  781. Value *getStepVector(Value *Val, int StartIdx, Value *Step,
  782. Instruction::BinaryOps Opcode =
  783. Instruction::BinaryOpsEnd) override;
  784. Value *reverseVector(Value *Vec) override;
  785. };
  786. /// Encapsulate information regarding vectorization of a loop and its epilogue.
  787. /// This information is meant to be updated and used across two stages of
  788. /// epilogue vectorization.
  789. struct EpilogueLoopVectorizationInfo {
  790. ElementCount MainLoopVF = ElementCount::getFixed(0);
  791. unsigned MainLoopUF = 0;
  792. ElementCount EpilogueVF = ElementCount::getFixed(0);
  793. unsigned EpilogueUF = 0;
  794. BasicBlock *MainLoopIterationCountCheck = nullptr;
  795. BasicBlock *EpilogueIterationCountCheck = nullptr;
  796. BasicBlock *SCEVSafetyCheck = nullptr;
  797. BasicBlock *MemSafetyCheck = nullptr;
  798. Value *TripCount = nullptr;
  799. Value *VectorTripCount = nullptr;
  800. EpilogueLoopVectorizationInfo(unsigned MVF, unsigned MUF, unsigned EVF,
  801. unsigned EUF)
  802. : MainLoopVF(ElementCount::getFixed(MVF)), MainLoopUF(MUF),
  803. EpilogueVF(ElementCount::getFixed(EVF)), EpilogueUF(EUF) {
  804. assert(EUF == 1 &&
  805. "A high UF for the epilogue loop is likely not beneficial.");
  806. }
  807. };
  808. /// An extension of the inner loop vectorizer that creates a skeleton for a
  809. /// vectorized loop that has its epilogue (residual) also vectorized.
  810. /// The idea is to run the vplan on a given loop twice, firstly to setup the
  811. /// skeleton and vectorize the main loop, and secondly to complete the skeleton
  812. /// from the first step and vectorize the epilogue. This is achieved by
  813. /// deriving two concrete strategy classes from this base class and invoking
  814. /// them in succession from the loop vectorizer planner.
  815. class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
  816. public:
  817. InnerLoopAndEpilogueVectorizer(
  818. Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
  819. DominatorTree *DT, const TargetLibraryInfo *TLI,
  820. const TargetTransformInfo *TTI, AssumptionCache *AC,
  821. OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
  822. LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
  823. BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI)
  824. : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
  825. EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI),
  826. EPI(EPI) {}
  827. // Override this function to handle the more complex control flow around the
  828. // three loops.
  829. BasicBlock *createVectorizedLoopSkeleton() final override {
  830. return createEpilogueVectorizedLoopSkeleton();
  831. }
  832. /// The interface for creating a vectorized skeleton using one of two
  833. /// different strategies, each corresponding to one execution of the vplan
  834. /// as described above.
  835. virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
  836. /// Holds and updates state information required to vectorize the main loop
  837. /// and its epilogue in two separate passes. This setup helps us avoid
  838. /// regenerating and recomputing runtime safety checks. It also helps us to
  839. /// shorten the iteration-count-check path length for the cases where the
  840. /// iteration count of the loop is so small that the main vector loop is
  841. /// completely skipped.
  842. EpilogueLoopVectorizationInfo &EPI;
  843. };
  844. /// A specialized derived class of inner loop vectorizer that performs
  845. /// vectorization of *main* loops in the process of vectorizing loops and their
  846. /// epilogues.
  847. class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
  848. public:
  849. EpilogueVectorizerMainLoop(
  850. Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
  851. DominatorTree *DT, const TargetLibraryInfo *TLI,
  852. const TargetTransformInfo *TTI, AssumptionCache *AC,
  853. OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
  854. LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
  855. BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI)
  856. : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
  857. EPI, LVL, CM, BFI, PSI) {}
  858. /// Implements the interface for creating a vectorized skeleton using the
  859. /// *main loop* strategy (ie the first pass of vplan execution).
  860. BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
  861. protected:
  862. /// Emits an iteration count bypass check once for the main loop (when \p
  863. /// ForEpilogue is false) and once for the epilogue loop (when \p
  864. /// ForEpilogue is true).
  865. BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
  866. bool ForEpilogue);
  867. void printDebugTracesAtStart() override;
  868. void printDebugTracesAtEnd() override;
  869. };
  870. // A specialized derived class of inner loop vectorizer that performs
  871. // vectorization of *epilogue* loops in the process of vectorizing loops and
  872. // their epilogues.
  873. class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
  874. public:
  875. EpilogueVectorizerEpilogueLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  876. LoopInfo *LI, DominatorTree *DT,
  877. const TargetLibraryInfo *TLI,
  878. const TargetTransformInfo *TTI, AssumptionCache *AC,
  879. OptimizationRemarkEmitter *ORE,
  880. EpilogueLoopVectorizationInfo &EPI,
  881. LoopVectorizationLegality *LVL,
  882. llvm::LoopVectorizationCostModel *CM,
  883. BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI)
  884. : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
  885. EPI, LVL, CM, BFI, PSI) {}
  886. /// Implements the interface for creating a vectorized skeleton using the
  887. /// *epilogue loop* strategy (ie the second pass of vplan execution).
  888. BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
  889. protected:
  890. /// Emits an iteration count bypass check after the main vector loop has
  891. /// finished to see if there are any iterations left to execute by either
  892. /// the vector epilogue or the scalar epilogue.
  893. BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
  894. BasicBlock *Bypass,
  895. BasicBlock *Insert);
  896. void printDebugTracesAtStart() override;
  897. void printDebugTracesAtEnd() override;
  898. };
  899. } // end namespace llvm
  900. /// Look for a meaningful debug location on the instruction or it's
  901. /// operands.
  902. static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
  903. if (!I)
  904. return I;
  905. DebugLoc Empty;
  906. if (I->getDebugLoc() != Empty)
  907. return I;
  908. for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
  909. if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
  910. if (OpInst->getDebugLoc() != Empty)
  911. return OpInst;
  912. }
  913. return I;
  914. }
  915. void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
  916. if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
  917. const DILocation *DIL = Inst->getDebugLoc();
  918. if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
  919. !isa<DbgInfoIntrinsic>(Inst)) {
  920. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  921. auto NewDIL =
  922. DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
  923. if (NewDIL)
  924. B.SetCurrentDebugLocation(NewDIL.getValue());
  925. else
  926. LLVM_DEBUG(dbgs()
  927. << "Failed to create new discriminator: "
  928. << DIL->getFilename() << " Line: " << DIL->getLine());
  929. }
  930. else
  931. B.SetCurrentDebugLocation(DIL);
  932. } else
  933. B.SetCurrentDebugLocation(DebugLoc());
  934. }
  935. /// Write a record \p DebugMsg about vectorization failure to the debug
  936. /// output stream. If \p I is passed, it is an instruction that prevents
  937. /// vectorization.
  938. #ifndef NDEBUG
  939. static void debugVectorizationFailure(const StringRef DebugMsg,
  940. Instruction *I) {
  941. dbgs() << "LV: Not vectorizing: " << DebugMsg;
  942. if (I != nullptr)
  943. dbgs() << " " << *I;
  944. else
  945. dbgs() << '.';
  946. dbgs() << '\n';
  947. }
  948. #endif
  949. /// Create an analysis remark that explains why vectorization failed
  950. ///
  951. /// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
  952. /// RemarkName is the identifier for the remark. If \p I is passed it is an
  953. /// instruction that prevents vectorization. Otherwise \p TheLoop is used for
  954. /// the location of the remark. \return the remark object that can be
  955. /// streamed to.
  956. static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
  957. StringRef RemarkName, Loop *TheLoop, Instruction *I) {
  958. Value *CodeRegion = TheLoop->getHeader();
  959. DebugLoc DL = TheLoop->getStartLoc();
  960. if (I) {
  961. CodeRegion = I->getParent();
  962. // If there is no debug location attached to the instruction, revert back to
  963. // using the loop's.
  964. if (I->getDebugLoc())
  965. DL = I->getDebugLoc();
  966. }
  967. OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
  968. R << "loop not vectorized: ";
  969. return R;
  970. }
  971. /// Return a value for Step multiplied by VF.
  972. static Value *createStepForVF(IRBuilder<> &B, Constant *Step, ElementCount VF) {
  973. assert(isa<ConstantInt>(Step) && "Expected an integer step");
  974. Constant *StepVal = ConstantInt::get(
  975. Step->getType(),
  976. cast<ConstantInt>(Step)->getSExtValue() * VF.getKnownMinValue());
  977. return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
  978. }
  979. namespace llvm {
  980. void reportVectorizationFailure(const StringRef DebugMsg,
  981. const StringRef OREMsg, const StringRef ORETag,
  982. OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I) {
  983. LLVM_DEBUG(debugVectorizationFailure(DebugMsg, I));
  984. LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
  985. ORE->emit(createLVAnalysis(Hints.vectorizeAnalysisPassName(),
  986. ORETag, TheLoop, I) << OREMsg);
  987. }
  988. } // end namespace llvm
  989. #ifndef NDEBUG
  990. /// \return string containing a file name and a line # for the given loop.
  991. static std::string getDebugLocString(const Loop *L) {
  992. std::string Result;
  993. if (L) {
  994. raw_string_ostream OS(Result);
  995. if (const DebugLoc LoopDbgLoc = L->getStartLoc())
  996. LoopDbgLoc.print(OS);
  997. else
  998. // Just print the module name.
  999. OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
  1000. OS.flush();
  1001. }
  1002. return Result;
  1003. }
  1004. #endif
  1005. void InnerLoopVectorizer::addNewMetadata(Instruction *To,
  1006. const Instruction *Orig) {
  1007. // If the loop was versioned with memchecks, add the corresponding no-alias
  1008. // metadata.
  1009. if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
  1010. LVer->annotateInstWithNoAlias(To, Orig);
  1011. }
  1012. void InnerLoopVectorizer::addMetadata(Instruction *To,
  1013. Instruction *From) {
  1014. propagateMetadata(To, From);
  1015. addNewMetadata(To, From);
  1016. }
  1017. void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
  1018. Instruction *From) {
  1019. for (Value *V : To) {
  1020. if (Instruction *I = dyn_cast<Instruction>(V))
  1021. addMetadata(I, From);
  1022. }
  1023. }
  1024. namespace llvm {
  1025. // Loop vectorization cost-model hints how the scalar epilogue loop should be
  1026. // lowered.
  1027. enum ScalarEpilogueLowering {
  1028. // The default: allowing scalar epilogues.
  1029. CM_ScalarEpilogueAllowed,
  1030. // Vectorization with OptForSize: don't allow epilogues.
  1031. CM_ScalarEpilogueNotAllowedOptSize,
  1032. // A special case of vectorisation with OptForSize: loops with a very small
  1033. // trip count are considered for vectorization under OptForSize, thereby
  1034. // making sure the cost of their loop body is dominant, free of runtime
  1035. // guards and scalar iteration overheads.
  1036. CM_ScalarEpilogueNotAllowedLowTripLoop,
  1037. // Loop hint predicate indicating an epilogue is undesired.
  1038. CM_ScalarEpilogueNotNeededUsePredicate,
  1039. // Directive indicating we must either tail fold or not vectorize
  1040. CM_ScalarEpilogueNotAllowedUsePredicate
  1041. };
  1042. /// LoopVectorizationCostModel - estimates the expected speedups due to
  1043. /// vectorization.
  1044. /// In many cases vectorization is not profitable. This can happen because of
  1045. /// a number of reasons. In this class we mainly attempt to predict the
  1046. /// expected speedup/slowdowns due to the supported instruction set. We use the
  1047. /// TargetTransformInfo to query the different backends for the cost of
  1048. /// different operations.
  1049. class LoopVectorizationCostModel {
  1050. public:
  1051. LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
  1052. PredicatedScalarEvolution &PSE, LoopInfo *LI,
  1053. LoopVectorizationLegality *Legal,
  1054. const TargetTransformInfo &TTI,
  1055. const TargetLibraryInfo *TLI, DemandedBits *DB,
  1056. AssumptionCache *AC,
  1057. OptimizationRemarkEmitter *ORE, const Function *F,
  1058. const LoopVectorizeHints *Hints,
  1059. InterleavedAccessInfo &IAI)
  1060. : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
  1061. TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
  1062. Hints(Hints), InterleaveInfo(IAI) {}
  1063. /// \return An upper bound for the vectorization factor, or None if
  1064. /// vectorization and interleaving should be avoided up front.
  1065. Optional<ElementCount> computeMaxVF(ElementCount UserVF, unsigned UserIC);
  1066. /// \return True if runtime checks are required for vectorization, and false
  1067. /// otherwise.
  1068. bool runtimeChecksRequired();
  1069. /// \return The most profitable vectorization factor and the cost of that VF.
  1070. /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
  1071. /// then this vectorization factor will be selected if vectorization is
  1072. /// possible.
  1073. VectorizationFactor selectVectorizationFactor(ElementCount MaxVF);
  1074. VectorizationFactor
  1075. selectEpilogueVectorizationFactor(const ElementCount MaxVF,
  1076. const LoopVectorizationPlanner &LVP);
  1077. /// Setup cost-based decisions for user vectorization factor.
  1078. void selectUserVectorizationFactor(ElementCount UserVF) {
  1079. collectUniformsAndScalars(UserVF);
  1080. collectInstsToScalarize(UserVF);
  1081. }
  1082. /// \return The size (in bits) of the smallest and widest types in the code
  1083. /// that needs to be vectorized. We ignore values that remain scalar such as
  1084. /// 64 bit loop indices.
  1085. std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
  1086. /// \return The desired interleave count.
  1087. /// If interleave count has been specified by metadata it will be returned.
  1088. /// Otherwise, the interleave count is computed and returned. VF and LoopCost
  1089. /// are the selected vectorization factor and the cost of the selected VF.
  1090. unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
  1091. /// Memory access instruction may be vectorized in more than one way.
  1092. /// Form of instruction after vectorization depends on cost.
  1093. /// This function takes cost-based decisions for Load/Store instructions
  1094. /// and collects them in a map. This decisions map is used for building
  1095. /// the lists of loop-uniform and loop-scalar instructions.
  1096. /// The calculated cost is saved with widening decision in order to
  1097. /// avoid redundant calculations.
  1098. void setCostBasedWideningDecision(ElementCount VF);
  1099. /// A struct that represents some properties of the register usage
  1100. /// of a loop.
  1101. struct RegisterUsage {
  1102. /// Holds the number of loop invariant values that are used in the loop.
  1103. /// The key is ClassID of target-provided register class.
  1104. SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
  1105. /// Holds the maximum number of concurrent live intervals in the loop.
  1106. /// The key is ClassID of target-provided register class.
  1107. SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
  1108. };
  1109. /// \return Returns information about the register usages of the loop for the
  1110. /// given vectorization factors.
  1111. SmallVector<RegisterUsage, 8>
  1112. calculateRegisterUsage(ArrayRef<ElementCount> VFs);
  1113. /// Collect values we want to ignore in the cost model.
  1114. void collectValuesToIgnore();
  1115. /// Split reductions into those that happen in the loop, and those that happen
  1116. /// outside. In loop reductions are collected into InLoopReductionChains.
  1117. void collectInLoopReductions();
  1118. /// \returns The smallest bitwidth each instruction can be represented with.
  1119. /// The vector equivalents of these instructions should be truncated to this
  1120. /// type.
  1121. const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
  1122. return MinBWs;
  1123. }
  1124. /// \returns True if it is more profitable to scalarize instruction \p I for
  1125. /// vectorization factor \p VF.
  1126. bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
  1127. assert(VF.isVector() &&
  1128. "Profitable to scalarize relevant only for VF > 1.");
  1129. // Cost model is not run in the VPlan-native path - return conservative
  1130. // result until this changes.
  1131. if (EnableVPlanNativePath)
  1132. return false;
  1133. auto Scalars = InstsToScalarize.find(VF);
  1134. assert(Scalars != InstsToScalarize.end() &&
  1135. "VF not yet analyzed for scalarization profitability");
  1136. return Scalars->second.find(I) != Scalars->second.end();
  1137. }
  1138. /// Returns true if \p I is known to be uniform after vectorization.
  1139. bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
  1140. if (VF.isScalar())
  1141. return true;
  1142. // Cost model is not run in the VPlan-native path - return conservative
  1143. // result until this changes.
  1144. if (EnableVPlanNativePath)
  1145. return false;
  1146. auto UniformsPerVF = Uniforms.find(VF);
  1147. assert(UniformsPerVF != Uniforms.end() &&
  1148. "VF not yet analyzed for uniformity");
  1149. return UniformsPerVF->second.count(I);
  1150. }
  1151. /// Returns true if \p I is known to be scalar after vectorization.
  1152. bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
  1153. if (VF.isScalar())
  1154. return true;
  1155. // Cost model is not run in the VPlan-native path - return conservative
  1156. // result until this changes.
  1157. if (EnableVPlanNativePath)
  1158. return false;
  1159. auto ScalarsPerVF = Scalars.find(VF);
  1160. assert(ScalarsPerVF != Scalars.end() &&
  1161. "Scalar values are not calculated for VF");
  1162. return ScalarsPerVF->second.count(I);
  1163. }
  1164. /// \returns True if instruction \p I can be truncated to a smaller bitwidth
  1165. /// for vectorization factor \p VF.
  1166. bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
  1167. return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
  1168. !isProfitableToScalarize(I, VF) &&
  1169. !isScalarAfterVectorization(I, VF);
  1170. }
  1171. /// Decision that was taken during cost calculation for memory instruction.
  1172. enum InstWidening {
  1173. CM_Unknown,
  1174. CM_Widen, // For consecutive accesses with stride +1.
  1175. CM_Widen_Reverse, // For consecutive accesses with stride -1.
  1176. CM_Interleave,
  1177. CM_GatherScatter,
  1178. CM_Scalarize
  1179. };
  1180. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  1181. /// instruction \p I and vector width \p VF.
  1182. void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
  1183. InstructionCost Cost) {
  1184. assert(VF.isVector() && "Expected VF >=2");
  1185. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  1186. }
  1187. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  1188. /// interleaving group \p Grp and vector width \p VF.
  1189. void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
  1190. ElementCount VF, InstWidening W,
  1191. InstructionCost Cost) {
  1192. assert(VF.isVector() && "Expected VF >=2");
  1193. /// Broadcast this decicion to all instructions inside the group.
  1194. /// But the cost will be assigned to one instruction only.
  1195. for (unsigned i = 0; i < Grp->getFactor(); ++i) {
  1196. if (auto *I = Grp->getMember(i)) {
  1197. if (Grp->getInsertPos() == I)
  1198. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  1199. else
  1200. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
  1201. }
  1202. }
  1203. }
  1204. /// Return the cost model decision for the given instruction \p I and vector
  1205. /// width \p VF. Return CM_Unknown if this instruction did not pass
  1206. /// through the cost modeling.
  1207. InstWidening getWideningDecision(Instruction *I, ElementCount VF) {
  1208. assert(VF.isVector() && "Expected VF to be a vector VF");
  1209. // Cost model is not run in the VPlan-native path - return conservative
  1210. // result until this changes.
  1211. if (EnableVPlanNativePath)
  1212. return CM_GatherScatter;
  1213. std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
  1214. auto Itr = WideningDecisions.find(InstOnVF);
  1215. if (Itr == WideningDecisions.end())
  1216. return CM_Unknown;
  1217. return Itr->second.first;
  1218. }
  1219. /// Return the vectorization cost for the given instruction \p I and vector
  1220. /// width \p VF.
  1221. InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
  1222. assert(VF.isVector() && "Expected VF >=2");
  1223. std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
  1224. assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
  1225. "The cost is not calculated");
  1226. return WideningDecisions[InstOnVF].second;
  1227. }
  1228. /// Return True if instruction \p I is an optimizable truncate whose operand
  1229. /// is an induction variable. Such a truncate will be removed by adding a new
  1230. /// induction variable with the destination type.
  1231. bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
  1232. // If the instruction is not a truncate, return false.
  1233. auto *Trunc = dyn_cast<TruncInst>(I);
  1234. if (!Trunc)
  1235. return false;
  1236. // Get the source and destination types of the truncate.
  1237. Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
  1238. Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
  1239. // If the truncate is free for the given types, return false. Replacing a
  1240. // free truncate with an induction variable would add an induction variable
  1241. // update instruction to each iteration of the loop. We exclude from this
  1242. // check the primary induction variable since it will need an update
  1243. // instruction regardless.
  1244. Value *Op = Trunc->getOperand(0);
  1245. if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
  1246. return false;
  1247. // If the truncated value is not an induction variable, return false.
  1248. return Legal->isInductionPhi(Op);
  1249. }
  1250. /// Collects the instructions to scalarize for each predicated instruction in
  1251. /// the loop.
  1252. void collectInstsToScalarize(ElementCount VF);
  1253. /// Collect Uniform and Scalar values for the given \p VF.
  1254. /// The sets depend on CM decision for Load/Store instructions
  1255. /// that may be vectorized as interleave, gather-scatter or scalarized.
  1256. void collectUniformsAndScalars(ElementCount VF) {
  1257. // Do the analysis once.
  1258. if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
  1259. return;
  1260. setCostBasedWideningDecision(VF);
  1261. collectLoopUniforms(VF);
  1262. collectLoopScalars(VF);
  1263. }
  1264. /// Returns true if the target machine supports masked store operation
  1265. /// for the given \p DataType and kind of access to \p Ptr.
  1266. bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) {
  1267. return Legal->isConsecutivePtr(Ptr) &&
  1268. TTI.isLegalMaskedStore(DataType, Alignment);
  1269. }
  1270. /// Returns true if the target machine supports masked load operation
  1271. /// for the given \p DataType and kind of access to \p Ptr.
  1272. bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) {
  1273. return Legal->isConsecutivePtr(Ptr) &&
  1274. TTI.isLegalMaskedLoad(DataType, Alignment);
  1275. }
  1276. /// Returns true if the target machine supports masked scatter operation
  1277. /// for the given \p DataType.
  1278. bool isLegalMaskedScatter(Type *DataType, Align Alignment) {
  1279. return TTI.isLegalMaskedScatter(DataType, Alignment);
  1280. }
  1281. /// Returns true if the target machine supports masked gather operation
  1282. /// for the given \p DataType.
  1283. bool isLegalMaskedGather(Type *DataType, Align Alignment) {
  1284. return TTI.isLegalMaskedGather(DataType, Alignment);
  1285. }
  1286. /// Returns true if the target machine can represent \p V as a masked gather
  1287. /// or scatter operation.
  1288. bool isLegalGatherOrScatter(Value *V) {
  1289. bool LI = isa<LoadInst>(V);
  1290. bool SI = isa<StoreInst>(V);
  1291. if (!LI && !SI)
  1292. return false;
  1293. auto *Ty = getMemInstValueType(V);
  1294. Align Align = getLoadStoreAlignment(V);
  1295. return (LI && isLegalMaskedGather(Ty, Align)) ||
  1296. (SI && isLegalMaskedScatter(Ty, Align));
  1297. }
  1298. /// Returns true if \p I is an instruction that will be scalarized with
  1299. /// predication. Such instructions include conditional stores and
  1300. /// instructions that may divide by zero.
  1301. /// If a non-zero VF has been calculated, we check if I will be scalarized
  1302. /// predication for that VF.
  1303. bool isScalarWithPredication(Instruction *I,
  1304. ElementCount VF = ElementCount::getFixed(1));
  1305. // Returns true if \p I is an instruction that will be predicated either
  1306. // through scalar predication or masked load/store or masked gather/scatter.
  1307. // Superset of instructions that return true for isScalarWithPredication.
  1308. bool isPredicatedInst(Instruction *I) {
  1309. if (!blockNeedsPredication(I->getParent()))
  1310. return false;
  1311. // Loads and stores that need some form of masked operation are predicated
  1312. // instructions.
  1313. if (isa<LoadInst>(I) || isa<StoreInst>(I))
  1314. return Legal->isMaskRequired(I);
  1315. return isScalarWithPredication(I);
  1316. }
  1317. /// Returns true if \p I is a memory instruction with consecutive memory
  1318. /// access that can be widened.
  1319. bool
  1320. memoryInstructionCanBeWidened(Instruction *I,
  1321. ElementCount VF = ElementCount::getFixed(1));
  1322. /// Returns true if \p I is a memory instruction in an interleaved-group
  1323. /// of memory accesses that can be vectorized with wide vector loads/stores
  1324. /// and shuffles.
  1325. bool
  1326. interleavedAccessCanBeWidened(Instruction *I,
  1327. ElementCount VF = ElementCount::getFixed(1));
  1328. /// Check if \p Instr belongs to any interleaved access group.
  1329. bool isAccessInterleaved(Instruction *Instr) {
  1330. return InterleaveInfo.isInterleaved(Instr);
  1331. }
  1332. /// Get the interleaved access group that \p Instr belongs to.
  1333. const InterleaveGroup<Instruction> *
  1334. getInterleavedAccessGroup(Instruction *Instr) {
  1335. return InterleaveInfo.getInterleaveGroup(Instr);
  1336. }
  1337. /// Returns true if we're required to use a scalar epilogue for at least
  1338. /// the final iteration of the original loop.
  1339. bool requiresScalarEpilogue() const {
  1340. if (!isScalarEpilogueAllowed())
  1341. return false;
  1342. // If we might exit from anywhere but the latch, must run the exiting
  1343. // iteration in scalar form.
  1344. if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
  1345. return true;
  1346. return InterleaveInfo.requiresScalarEpilogue();
  1347. }
  1348. /// Returns true if a scalar epilogue is not allowed due to optsize or a
  1349. /// loop hint annotation.
  1350. bool isScalarEpilogueAllowed() const {
  1351. return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
  1352. }
  1353. /// Returns true if all loop blocks should be masked to fold tail loop.
  1354. bool foldTailByMasking() const { return FoldTailByMasking; }
  1355. bool blockNeedsPredication(BasicBlock *BB) {
  1356. return foldTailByMasking() || Legal->blockNeedsPredication(BB);
  1357. }
  1358. /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
  1359. /// nodes to the chain of instructions representing the reductions. Uses a
  1360. /// MapVector to ensure deterministic iteration order.
  1361. using ReductionChainMap =
  1362. SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
  1363. /// Return the chain of instructions representing an inloop reduction.
  1364. const ReductionChainMap &getInLoopReductionChains() const {
  1365. return InLoopReductionChains;
  1366. }
  1367. /// Returns true if the Phi is part of an inloop reduction.
  1368. bool isInLoopReduction(PHINode *Phi) const {
  1369. return InLoopReductionChains.count(Phi);
  1370. }
  1371. /// Estimate cost of an intrinsic call instruction CI if it were vectorized
  1372. /// with factor VF. Return the cost of the instruction, including
  1373. /// scalarization overhead if it's needed.
  1374. InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF);
  1375. /// Estimate cost of a call instruction CI if it were vectorized with factor
  1376. /// VF. Return the cost of the instruction, including scalarization overhead
  1377. /// if it's needed. The flag NeedToScalarize shows if the call needs to be
  1378. /// scalarized -
  1379. /// i.e. either vector version isn't available, or is too expensive.
  1380. InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
  1381. bool &NeedToScalarize);
  1382. /// Invalidates decisions already taken by the cost model.
  1383. void invalidateCostModelingDecisions() {
  1384. WideningDecisions.clear();
  1385. Uniforms.clear();
  1386. Scalars.clear();
  1387. }
  1388. private:
  1389. unsigned NumPredStores = 0;
  1390. /// \return An upper bound for the vectorization factor, a power-of-2 larger
  1391. /// than zero. One is returned if vectorization should best be avoided due
  1392. /// to cost.
  1393. ElementCount computeFeasibleMaxVF(unsigned ConstTripCount,
  1394. ElementCount UserVF);
  1395. /// The vectorization cost is a combination of the cost itself and a boolean
  1396. /// indicating whether any of the contributing operations will actually
  1397. /// operate on
  1398. /// vector values after type legalization in the backend. If this latter value
  1399. /// is
  1400. /// false, then all operations will be scalarized (i.e. no vectorization has
  1401. /// actually taken place).
  1402. using VectorizationCostTy = std::pair<InstructionCost, bool>;
  1403. /// Returns the expected execution cost. The unit of the cost does
  1404. /// not matter because we use the 'cost' units to compare different
  1405. /// vector widths. The cost that is returned is *not* normalized by
  1406. /// the factor width.
  1407. VectorizationCostTy expectedCost(ElementCount VF);
  1408. /// Returns the execution time cost of an instruction for a given vector
  1409. /// width. Vector width of one means scalar.
  1410. VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
  1411. /// The cost-computation logic from getInstructionCost which provides
  1412. /// the vector type as an output parameter.
  1413. InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
  1414. Type *&VectorTy);
  1415. /// Return the cost of instructions in an inloop reduction pattern, if I is
  1416. /// part of that pattern.
  1417. InstructionCost getReductionPatternCost(Instruction *I, ElementCount VF,
  1418. Type *VectorTy,
  1419. TTI::TargetCostKind CostKind);
  1420. /// Calculate vectorization cost of memory instruction \p I.
  1421. InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
  1422. /// The cost computation for scalarized memory instruction.
  1423. InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
  1424. /// The cost computation for interleaving group of memory instructions.
  1425. InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
  1426. /// The cost computation for Gather/Scatter instruction.
  1427. InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
  1428. /// The cost computation for widening instruction \p I with consecutive
  1429. /// memory access.
  1430. InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
  1431. /// The cost calculation for Load/Store instruction \p I with uniform pointer -
  1432. /// Load: scalar load + broadcast.
  1433. /// Store: scalar store + (loop invariant value stored? 0 : extract of last
  1434. /// element)
  1435. InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
  1436. /// Estimate the overhead of scalarizing an instruction. This is a
  1437. /// convenience wrapper for the type-based getScalarizationOverhead API.
  1438. InstructionCost getScalarizationOverhead(Instruction *I, ElementCount VF);
  1439. /// Returns whether the instruction is a load or store and will be a emitted
  1440. /// as a vector operation.
  1441. bool isConsecutiveLoadOrStore(Instruction *I);
  1442. /// Returns true if an artificially high cost for emulated masked memrefs
  1443. /// should be used.
  1444. bool useEmulatedMaskMemRefHack(Instruction *I);
  1445. /// Map of scalar integer values to the smallest bitwidth they can be legally
  1446. /// represented as. The vector equivalents of these values should be truncated
  1447. /// to this type.
  1448. MapVector<Instruction *, uint64_t> MinBWs;
  1449. /// A type representing the costs for instructions if they were to be
  1450. /// scalarized rather than vectorized. The entries are Instruction-Cost
  1451. /// pairs.
  1452. using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
  1453. /// A set containing all BasicBlocks that are known to present after
  1454. /// vectorization as a predicated block.
  1455. SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
  1456. /// Records whether it is allowed to have the original scalar loop execute at
  1457. /// least once. This may be needed as a fallback loop in case runtime
  1458. /// aliasing/dependence checks fail, or to handle the tail/remainder
  1459. /// iterations when the trip count is unknown or doesn't divide by the VF,
  1460. /// or as a peel-loop to handle gaps in interleave-groups.
  1461. /// Under optsize and when the trip count is very small we don't allow any
  1462. /// iterations to execute in the scalar loop.
  1463. ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
  1464. /// All blocks of loop are to be masked to fold tail of scalar iterations.
  1465. bool FoldTailByMasking = false;
  1466. /// A map holding scalar costs for different vectorization factors. The
  1467. /// presence of a cost for an instruction in the mapping indicates that the
  1468. /// instruction will be scalarized when vectorizing with the associated
  1469. /// vectorization factor. The entries are VF-ScalarCostTy pairs.
  1470. DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
  1471. /// Holds the instructions known to be uniform after vectorization.
  1472. /// The data is collected per VF.
  1473. DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
  1474. /// Holds the instructions known to be scalar after vectorization.
  1475. /// The data is collected per VF.
  1476. DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
  1477. /// Holds the instructions (address computations) that are forced to be
  1478. /// scalarized.
  1479. DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
  1480. /// PHINodes of the reductions that should be expanded in-loop along with
  1481. /// their associated chains of reduction operations, in program order from top
  1482. /// (PHI) to bottom
  1483. ReductionChainMap InLoopReductionChains;
  1484. /// A Map of inloop reduction operations and their immediate chain operand.
  1485. /// FIXME: This can be removed once reductions can be costed correctly in
  1486. /// vplan. This was added to allow quick lookup to the inloop operations,
  1487. /// without having to loop through InLoopReductionChains.
  1488. DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
  1489. /// Returns the expected difference in cost from scalarizing the expression
  1490. /// feeding a predicated instruction \p PredInst. The instructions to
  1491. /// scalarize and their scalar costs are collected in \p ScalarCosts. A
  1492. /// non-negative return value implies the expression will be scalarized.
  1493. /// Currently, only single-use chains are considered for scalarization.
  1494. int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
  1495. ElementCount VF);
  1496. /// Collect the instructions that are uniform after vectorization. An
  1497. /// instruction is uniform if we represent it with a single scalar value in
  1498. /// the vectorized loop corresponding to each vector iteration. Examples of
  1499. /// uniform instructions include pointer operands of consecutive or
  1500. /// interleaved memory accesses. Note that although uniformity implies an
  1501. /// instruction will be scalar, the reverse is not true. In general, a
  1502. /// scalarized instruction will be represented by VF scalar values in the
  1503. /// vectorized loop, each corresponding to an iteration of the original
  1504. /// scalar loop.
  1505. void collectLoopUniforms(ElementCount VF);
  1506. /// Collect the instructions that are scalar after vectorization. An
  1507. /// instruction is scalar if it is known to be uniform or will be scalarized
  1508. /// during vectorization. Non-uniform scalarized instructions will be
  1509. /// represented by VF values in the vectorized loop, each corresponding to an
  1510. /// iteration of the original scalar loop.
  1511. void collectLoopScalars(ElementCount VF);
  1512. /// Keeps cost model vectorization decision and cost for instructions.
  1513. /// Right now it is used for memory instructions only.
  1514. using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
  1515. std::pair<InstWidening, InstructionCost>>;
  1516. DecisionList WideningDecisions;
  1517. /// Returns true if \p V is expected to be vectorized and it needs to be
  1518. /// extracted.
  1519. bool needsExtract(Value *V, ElementCount VF) const {
  1520. Instruction *I = dyn_cast<Instruction>(V);
  1521. if (VF.isScalar() || !I || !TheLoop->contains(I) ||
  1522. TheLoop->isLoopInvariant(I))
  1523. return false;
  1524. // Assume we can vectorize V (and hence we need extraction) if the
  1525. // scalars are not computed yet. This can happen, because it is called
  1526. // via getScalarizationOverhead from setCostBasedWideningDecision, before
  1527. // the scalars are collected. That should be a safe assumption in most
  1528. // cases, because we check if the operands have vectorizable types
  1529. // beforehand in LoopVectorizationLegality.
  1530. return Scalars.find(VF) == Scalars.end() ||
  1531. !isScalarAfterVectorization(I, VF);
  1532. };
  1533. /// Returns a range containing only operands needing to be extracted.
  1534. SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
  1535. ElementCount VF) {
  1536. return SmallVector<Value *, 4>(make_filter_range(
  1537. Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
  1538. }
  1539. /// Determines if we have the infrastructure to vectorize loop \p L and its
  1540. /// epilogue, assuming the main loop is vectorized by \p VF.
  1541. bool isCandidateForEpilogueVectorization(const Loop &L,
  1542. const ElementCount VF) const;
  1543. /// Returns true if epilogue vectorization is considered profitable, and
  1544. /// false otherwise.
  1545. /// \p VF is the vectorization factor chosen for the original loop.
  1546. bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
  1547. public:
  1548. /// The loop that we evaluate.
  1549. Loop *TheLoop;
  1550. /// Predicated scalar evolution analysis.
  1551. PredicatedScalarEvolution &PSE;
  1552. /// Loop Info analysis.
  1553. LoopInfo *LI;
  1554. /// Vectorization legality.
  1555. LoopVectorizationLegality *Legal;
  1556. /// Vector target information.
  1557. const TargetTransformInfo &TTI;
  1558. /// Target Library Info.
  1559. const TargetLibraryInfo *TLI;
  1560. /// Demanded bits analysis.
  1561. DemandedBits *DB;
  1562. /// Assumption cache.
  1563. AssumptionCache *AC;
  1564. /// Interface to emit optimization remarks.
  1565. OptimizationRemarkEmitter *ORE;
  1566. const Function *TheFunction;
  1567. /// Loop Vectorize Hint.
  1568. const LoopVectorizeHints *Hints;
  1569. /// The interleave access information contains groups of interleaved accesses
  1570. /// with the same stride and close to each other.
  1571. InterleavedAccessInfo &InterleaveInfo;
  1572. /// Values to ignore in the cost model.
  1573. SmallPtrSet<const Value *, 16> ValuesToIgnore;
  1574. /// Values to ignore in the cost model when VF > 1.
  1575. SmallPtrSet<const Value *, 16> VecValuesToIgnore;
  1576. /// Profitable vector factors.
  1577. SmallVector<VectorizationFactor, 8> ProfitableVFs;
  1578. };
  1579. } // end namespace llvm
  1580. // Return true if \p OuterLp is an outer loop annotated with hints for explicit
  1581. // vectorization. The loop needs to be annotated with #pragma omp simd
  1582. // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
  1583. // vector length information is not provided, vectorization is not considered
  1584. // explicit. Interleave hints are not allowed either. These limitations will be
  1585. // relaxed in the future.
  1586. // Please, note that we are currently forced to abuse the pragma 'clang
  1587. // vectorize' semantics. This pragma provides *auto-vectorization hints*
  1588. // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
  1589. // provides *explicit vectorization hints* (LV can bypass legal checks and
  1590. // assume that vectorization is legal). However, both hints are implemented
  1591. // using the same metadata (llvm.loop.vectorize, processed by
  1592. // LoopVectorizeHints). This will be fixed in the future when the native IR
  1593. // representation for pragma 'omp simd' is introduced.
  1594. static bool isExplicitVecOuterLoop(Loop *OuterLp,
  1595. OptimizationRemarkEmitter *ORE) {
  1596. assert(!OuterLp->isInnermost() && "This is not an outer loop");
  1597. LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
  1598. // Only outer loops with an explicit vectorization hint are supported.
  1599. // Unannotated outer loops are ignored.
  1600. if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
  1601. return false;
  1602. Function *Fn = OuterLp->getHeader()->getParent();
  1603. if (!Hints.allowVectorization(Fn, OuterLp,
  1604. true /*VectorizeOnlyWhenForced*/)) {
  1605. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
  1606. return false;
  1607. }
  1608. if (Hints.getInterleave() > 1) {
  1609. // TODO: Interleave support is future work.
  1610. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
  1611. "outer loops.\n");
  1612. Hints.emitRemarkWithHints();
  1613. return false;
  1614. }
  1615. return true;
  1616. }
  1617. static void collectSupportedLoops(Loop &L, LoopInfo *LI,
  1618. OptimizationRemarkEmitter *ORE,
  1619. SmallVectorImpl<Loop *> &V) {
  1620. // Collect inner loops and outer loops without irreducible control flow. For
  1621. // now, only collect outer loops that have explicit vectorization hints. If we
  1622. // are stress testing the VPlan H-CFG construction, we collect the outermost
  1623. // loop of every loop nest.
  1624. if (L.isInnermost() || VPlanBuildStressTest ||
  1625. (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
  1626. LoopBlocksRPO RPOT(&L);
  1627. RPOT.perform(LI);
  1628. if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
  1629. V.push_back(&L);
  1630. // TODO: Collect inner loops inside marked outer loops in case
  1631. // vectorization fails for the outer loop. Do not invoke
  1632. // 'containsIrreducibleCFG' again for inner loops when the outer loop is
  1633. // already known to be reducible. We can use an inherited attribute for
  1634. // that.
  1635. return;
  1636. }
  1637. }
  1638. for (Loop *InnerL : L)
  1639. collectSupportedLoops(*InnerL, LI, ORE, V);
  1640. }
  1641. namespace {
  1642. /// The LoopVectorize Pass.
  1643. struct LoopVectorize : public FunctionPass {
  1644. /// Pass identification, replacement for typeid
  1645. static char ID;
  1646. LoopVectorizePass Impl;
  1647. explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
  1648. bool VectorizeOnlyWhenForced = false)
  1649. : FunctionPass(ID),
  1650. Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
  1651. initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
  1652. }
  1653. bool runOnFunction(Function &F) override {
  1654. if (skipFunction(F))
  1655. return false;
  1656. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  1657. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1658. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1659. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1660. auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
  1661. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  1662. auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
  1663. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  1664. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1665. auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
  1666. auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  1667. auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  1668. auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  1669. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  1670. [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
  1671. return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
  1672. GetLAA, *ORE, PSI).MadeAnyChange;
  1673. }
  1674. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1675. AU.addRequired<AssumptionCacheTracker>();
  1676. AU.addRequired<BlockFrequencyInfoWrapperPass>();
  1677. AU.addRequired<DominatorTreeWrapperPass>();
  1678. AU.addRequired<LoopInfoWrapperPass>();
  1679. AU.addRequired<ScalarEvolutionWrapperPass>();
  1680. AU.addRequired<TargetTransformInfoWrapperPass>();
  1681. AU.addRequired<AAResultsWrapperPass>();
  1682. AU.addRequired<LoopAccessLegacyAnalysis>();
  1683. AU.addRequired<DemandedBitsWrapperPass>();
  1684. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  1685. AU.addRequired<InjectTLIMappingsLegacy>();
  1686. // We currently do not preserve loopinfo/dominator analyses with outer loop
  1687. // vectorization. Until this is addressed, mark these analyses as preserved
  1688. // only for non-VPlan-native path.
  1689. // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
  1690. if (!EnableVPlanNativePath) {
  1691. AU.addPreserved<LoopInfoWrapperPass>();
  1692. AU.addPreserved<DominatorTreeWrapperPass>();
  1693. }
  1694. AU.addPreserved<BasicAAWrapperPass>();
  1695. AU.addPreserved<GlobalsAAWrapperPass>();
  1696. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  1697. }
  1698. };
  1699. } // end anonymous namespace
  1700. //===----------------------------------------------------------------------===//
  1701. // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
  1702. // LoopVectorizationCostModel and LoopVectorizationPlanner.
  1703. //===----------------------------------------------------------------------===//
  1704. Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
  1705. // We need to place the broadcast of invariant variables outside the loop,
  1706. // but only if it's proven safe to do so. Else, broadcast will be inside
  1707. // vector loop body.
  1708. Instruction *Instr = dyn_cast<Instruction>(V);
  1709. bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
  1710. (!Instr ||
  1711. DT->dominates(Instr->getParent(), LoopVectorPreHeader));
  1712. // Place the code for broadcasting invariant variables in the new preheader.
  1713. IRBuilder<>::InsertPointGuard Guard(Builder);
  1714. if (SafeToHoist)
  1715. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1716. // Broadcast the scalar into all locations in the vector.
  1717. Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
  1718. return Shuf;
  1719. }
  1720. void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
  1721. const InductionDescriptor &II, Value *Step, Value *Start,
  1722. Instruction *EntryVal) {
  1723. assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
  1724. "Expected either an induction phi-node or a truncate of it!");
  1725. // Construct the initial value of the vector IV in the vector loop preheader
  1726. auto CurrIP = Builder.saveIP();
  1727. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1728. if (isa<TruncInst>(EntryVal)) {
  1729. assert(Start->getType()->isIntegerTy() &&
  1730. "Truncation requires an integer type");
  1731. auto *TruncType = cast<IntegerType>(EntryVal->getType());
  1732. Step = Builder.CreateTrunc(Step, TruncType);
  1733. Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
  1734. }
  1735. Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
  1736. Value *SteppedStart =
  1737. getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
  1738. // We create vector phi nodes for both integer and floating-point induction
  1739. // variables. Here, we determine the kind of arithmetic we will perform.
  1740. Instruction::BinaryOps AddOp;
  1741. Instruction::BinaryOps MulOp;
  1742. if (Step->getType()->isIntegerTy()) {
  1743. AddOp = Instruction::Add;
  1744. MulOp = Instruction::Mul;
  1745. } else {
  1746. AddOp = II.getInductionOpcode();
  1747. MulOp = Instruction::FMul;
  1748. }
  1749. // Multiply the vectorization factor by the step using integer or
  1750. // floating-point arithmetic as appropriate.
  1751. Value *ConstVF =
  1752. getSignedIntOrFpConstant(Step->getType(), VF.getKnownMinValue());
  1753. Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
  1754. // Create a vector splat to use in the induction update.
  1755. //
  1756. // FIXME: If the step is non-constant, we create the vector splat with
  1757. // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
  1758. // handle a constant vector splat.
  1759. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  1760. Value *SplatVF = isa<Constant>(Mul)
  1761. ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
  1762. : Builder.CreateVectorSplat(VF, Mul);
  1763. Builder.restoreIP(CurrIP);
  1764. // We may need to add the step a number of times, depending on the unroll
  1765. // factor. The last of those goes into the PHI.
  1766. PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
  1767. &*LoopVectorBody->getFirstInsertionPt());
  1768. VecInd->setDebugLoc(EntryVal->getDebugLoc());
  1769. Instruction *LastInduction = VecInd;
  1770. for (unsigned Part = 0; Part < UF; ++Part) {
  1771. VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
  1772. if (isa<TruncInst>(EntryVal))
  1773. addMetadata(LastInduction, EntryVal);
  1774. recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, Part);
  1775. LastInduction = cast<Instruction>(addFastMathFlag(
  1776. Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
  1777. LastInduction->setDebugLoc(EntryVal->getDebugLoc());
  1778. }
  1779. // Move the last step to the end of the latch block. This ensures consistent
  1780. // placement of all induction updates.
  1781. auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
  1782. auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
  1783. auto *ICmp = cast<Instruction>(Br->getCondition());
  1784. LastInduction->moveBefore(ICmp);
  1785. LastInduction->setName("vec.ind.next");
  1786. VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
  1787. VecInd->addIncoming(LastInduction, LoopVectorLatch);
  1788. }
  1789. bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
  1790. return Cost->isScalarAfterVectorization(I, VF) ||
  1791. Cost->isProfitableToScalarize(I, VF);
  1792. }
  1793. bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
  1794. if (shouldScalarizeInstruction(IV))
  1795. return true;
  1796. auto isScalarInst = [&](User *U) -> bool {
  1797. auto *I = cast<Instruction>(U);
  1798. return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
  1799. };
  1800. return llvm::any_of(IV->users(), isScalarInst);
  1801. }
  1802. void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
  1803. const InductionDescriptor &ID, const Instruction *EntryVal,
  1804. Value *VectorLoopVal, unsigned Part, unsigned Lane) {
  1805. assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
  1806. "Expected either an induction phi-node or a truncate of it!");
  1807. // This induction variable is not the phi from the original loop but the
  1808. // newly-created IV based on the proof that casted Phi is equal to the
  1809. // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
  1810. // re-uses the same InductionDescriptor that original IV uses but we don't
  1811. // have to do any recording in this case - that is done when original IV is
  1812. // processed.
  1813. if (isa<TruncInst>(EntryVal))
  1814. return;
  1815. const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
  1816. if (Casts.empty())
  1817. return;
  1818. // Only the first Cast instruction in the Casts vector is of interest.
  1819. // The rest of the Casts (if exist) have no uses outside the
  1820. // induction update chain itself.
  1821. Instruction *CastInst = *Casts.begin();
  1822. if (Lane < UINT_MAX)
  1823. VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
  1824. else
  1825. VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
  1826. }
  1827. void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
  1828. TruncInst *Trunc) {
  1829. assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
  1830. "Primary induction variable must have an integer type");
  1831. auto II = Legal->getInductionVars().find(IV);
  1832. assert(II != Legal->getInductionVars().end() && "IV is not an induction");
  1833. auto ID = II->second;
  1834. assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
  1835. // The value from the original loop to which we are mapping the new induction
  1836. // variable.
  1837. Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
  1838. auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  1839. // Generate code for the induction step. Note that induction steps are
  1840. // required to be loop-invariant
  1841. auto CreateStepValue = [&](const SCEV *Step) -> Value * {
  1842. assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
  1843. "Induction step should be loop invariant");
  1844. if (PSE.getSE()->isSCEVable(IV->getType())) {
  1845. SCEVExpander Exp(*PSE.getSE(), DL, "induction");
  1846. return Exp.expandCodeFor(Step, Step->getType(),
  1847. LoopVectorPreHeader->getTerminator());
  1848. }
  1849. return cast<SCEVUnknown>(Step)->getValue();
  1850. };
  1851. // The scalar value to broadcast. This is derived from the canonical
  1852. // induction variable. If a truncation type is given, truncate the canonical
  1853. // induction variable and step. Otherwise, derive these values from the
  1854. // induction descriptor.
  1855. auto CreateScalarIV = [&](Value *&Step) -> Value * {
  1856. Value *ScalarIV = Induction;
  1857. if (IV != OldInduction) {
  1858. ScalarIV = IV->getType()->isIntegerTy()
  1859. ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
  1860. : Builder.CreateCast(Instruction::SIToFP, Induction,
  1861. IV->getType());
  1862. ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
  1863. ScalarIV->setName("offset.idx");
  1864. }
  1865. if (Trunc) {
  1866. auto *TruncType = cast<IntegerType>(Trunc->getType());
  1867. assert(Step->getType()->isIntegerTy() &&
  1868. "Truncation requires an integer step");
  1869. ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
  1870. Step = Builder.CreateTrunc(Step, TruncType);
  1871. }
  1872. return ScalarIV;
  1873. };
  1874. // Create the vector values from the scalar IV, in the absence of creating a
  1875. // vector IV.
  1876. auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
  1877. Value *Broadcasted = getBroadcastInstrs(ScalarIV);
  1878. for (unsigned Part = 0; Part < UF; ++Part) {
  1879. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  1880. Value *EntryPart =
  1881. getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
  1882. ID.getInductionOpcode());
  1883. VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
  1884. if (Trunc)
  1885. addMetadata(EntryPart, Trunc);
  1886. recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, Part);
  1887. }
  1888. };
  1889. // Now do the actual transformations, and start with creating the step value.
  1890. Value *Step = CreateStepValue(ID.getStep());
  1891. if (VF.isZero() || VF.isScalar()) {
  1892. Value *ScalarIV = CreateScalarIV(Step);
  1893. CreateSplatIV(ScalarIV, Step);
  1894. return;
  1895. }
  1896. // Determine if we want a scalar version of the induction variable. This is
  1897. // true if the induction variable itself is not widened, or if it has at
  1898. // least one user in the loop that is not widened.
  1899. auto NeedsScalarIV = needsScalarInduction(EntryVal);
  1900. if (!NeedsScalarIV) {
  1901. createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal);
  1902. return;
  1903. }
  1904. // Try to create a new independent vector induction variable. If we can't
  1905. // create the phi node, we will splat the scalar induction variable in each
  1906. // loop iteration.
  1907. if (!shouldScalarizeInstruction(EntryVal)) {
  1908. createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal);
  1909. Value *ScalarIV = CreateScalarIV(Step);
  1910. // Create scalar steps that can be used by instructions we will later
  1911. // scalarize. Note that the addition of the scalar steps will not increase
  1912. // the number of instructions in the loop in the common case prior to
  1913. // InstCombine. We will be trading one vector extract for each scalar step.
  1914. buildScalarSteps(ScalarIV, Step, EntryVal, ID);
  1915. return;
  1916. }
  1917. // All IV users are scalar instructions, so only emit a scalar IV, not a
  1918. // vectorised IV. Except when we tail-fold, then the splat IV feeds the
  1919. // predicate used by the masked loads/stores.
  1920. Value *ScalarIV = CreateScalarIV(Step);
  1921. if (!Cost->isScalarEpilogueAllowed())
  1922. CreateSplatIV(ScalarIV, Step);
  1923. buildScalarSteps(ScalarIV, Step, EntryVal, ID);
  1924. }
  1925. Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
  1926. Instruction::BinaryOps BinOp) {
  1927. // Create and check the types.
  1928. auto *ValVTy = cast<FixedVectorType>(Val->getType());
  1929. int VLen = ValVTy->getNumElements();
  1930. Type *STy = Val->getType()->getScalarType();
  1931. assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
  1932. "Induction Step must be an integer or FP");
  1933. assert(Step->getType() == STy && "Step has wrong type");
  1934. SmallVector<Constant *, 8> Indices;
  1935. if (STy->isIntegerTy()) {
  1936. // Create a vector of consecutive numbers from zero to VF.
  1937. for (int i = 0; i < VLen; ++i)
  1938. Indices.push_back(ConstantInt::get(STy, StartIdx + i));
  1939. // Add the consecutive indices to the vector value.
  1940. Constant *Cv = ConstantVector::get(Indices);
  1941. assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
  1942. Step = Builder.CreateVectorSplat(VLen, Step);
  1943. assert(Step->getType() == Val->getType() && "Invalid step vec");
  1944. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  1945. // which can be found from the original scalar operations.
  1946. Step = Builder.CreateMul(Cv, Step);
  1947. return Builder.CreateAdd(Val, Step, "induction");
  1948. }
  1949. // Floating point induction.
  1950. assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
  1951. "Binary Opcode should be specified for FP induction");
  1952. // Create a vector of consecutive numbers from zero to VF.
  1953. for (int i = 0; i < VLen; ++i)
  1954. Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
  1955. // Add the consecutive indices to the vector value.
  1956. Constant *Cv = ConstantVector::get(Indices);
  1957. Step = Builder.CreateVectorSplat(VLen, Step);
  1958. // Floating point operations had to be 'fast' to enable the induction.
  1959. FastMathFlags Flags;
  1960. Flags.setFast();
  1961. Value *MulOp = Builder.CreateFMul(Cv, Step);
  1962. if (isa<Instruction>(MulOp))
  1963. // Have to check, MulOp may be a constant
  1964. cast<Instruction>(MulOp)->setFastMathFlags(Flags);
  1965. Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
  1966. if (isa<Instruction>(BOp))
  1967. cast<Instruction>(BOp)->setFastMathFlags(Flags);
  1968. return BOp;
  1969. }
  1970. void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
  1971. Instruction *EntryVal,
  1972. const InductionDescriptor &ID) {
  1973. // We shouldn't have to build scalar steps if we aren't vectorizing.
  1974. assert(VF.isVector() && "VF should be greater than one");
  1975. // Get the value type and ensure it and the step have the same integer type.
  1976. Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
  1977. assert(ScalarIVTy == Step->getType() &&
  1978. "Val and Step should have the same type");
  1979. // We build scalar steps for both integer and floating-point induction
  1980. // variables. Here, we determine the kind of arithmetic we will perform.
  1981. Instruction::BinaryOps AddOp;
  1982. Instruction::BinaryOps MulOp;
  1983. if (ScalarIVTy->isIntegerTy()) {
  1984. AddOp = Instruction::Add;
  1985. MulOp = Instruction::Mul;
  1986. } else {
  1987. AddOp = ID.getInductionOpcode();
  1988. MulOp = Instruction::FMul;
  1989. }
  1990. // Determine the number of scalars we need to generate for each unroll
  1991. // iteration. If EntryVal is uniform, we only need to generate the first
  1992. // lane. Otherwise, we generate all VF values.
  1993. unsigned Lanes =
  1994. Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF)
  1995. ? 1
  1996. : VF.getKnownMinValue();
  1997. assert((!VF.isScalable() || Lanes == 1) &&
  1998. "Should never scalarize a scalable vector");
  1999. // Compute the scalar steps and save the results in VectorLoopValueMap.
  2000. for (unsigned Part = 0; Part < UF; ++Part) {
  2001. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  2002. auto *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
  2003. ScalarIVTy->getScalarSizeInBits());
  2004. Value *StartIdx =
  2005. createStepForVF(Builder, ConstantInt::get(IntStepTy, Part), VF);
  2006. if (ScalarIVTy->isFloatingPointTy())
  2007. StartIdx = Builder.CreateSIToFP(StartIdx, ScalarIVTy);
  2008. StartIdx = addFastMathFlag(Builder.CreateBinOp(
  2009. AddOp, StartIdx, getSignedIntOrFpConstant(ScalarIVTy, Lane)));
  2010. // The step returned by `createStepForVF` is a runtime-evaluated value
  2011. // when VF is scalable. Otherwise, it should be folded into a Constant.
  2012. assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
  2013. "Expected StartIdx to be folded to a constant when VF is not "
  2014. "scalable");
  2015. auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
  2016. auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
  2017. VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
  2018. recordVectorLoopValueForInductionCast(ID, EntryVal, Add, Part, Lane);
  2019. }
  2020. }
  2021. }
  2022. Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
  2023. assert(V != Induction && "The new induction variable should not be used.");
  2024. assert(!V->getType()->isVectorTy() && "Can't widen a vector");
  2025. assert(!V->getType()->isVoidTy() && "Type does not produce a value");
  2026. // If we have a stride that is replaced by one, do it here. Defer this for
  2027. // the VPlan-native path until we start running Legal checks in that path.
  2028. if (!EnableVPlanNativePath && Legal->hasStride(V))
  2029. V = ConstantInt::get(V->getType(), 1);
  2030. // If we have a vector mapped to this value, return it.
  2031. if (VectorLoopValueMap.hasVectorValue(V, Part))
  2032. return VectorLoopValueMap.getVectorValue(V, Part);
  2033. // If the value has not been vectorized, check if it has been scalarized
  2034. // instead. If it has been scalarized, and we actually need the value in
  2035. // vector form, we will construct the vector values on demand.
  2036. if (VectorLoopValueMap.hasAnyScalarValue(V)) {
  2037. Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
  2038. // If we've scalarized a value, that value should be an instruction.
  2039. auto *I = cast<Instruction>(V);
  2040. // If we aren't vectorizing, we can just copy the scalar map values over to
  2041. // the vector map.
  2042. if (VF.isScalar()) {
  2043. VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
  2044. return ScalarValue;
  2045. }
  2046. // Get the last scalar instruction we generated for V and Part. If the value
  2047. // is known to be uniform after vectorization, this corresponds to lane zero
  2048. // of the Part unroll iteration. Otherwise, the last instruction is the one
  2049. // we created for the last vector lane of the Part unroll iteration.
  2050. unsigned LastLane = Cost->isUniformAfterVectorization(I, VF)
  2051. ? 0
  2052. : VF.getKnownMinValue() - 1;
  2053. assert((!VF.isScalable() || LastLane == 0) &&
  2054. "Scalable vectorization can't lead to any scalarized values.");
  2055. auto *LastInst = cast<Instruction>(
  2056. VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
  2057. // Set the insert point after the last scalarized instruction. This ensures
  2058. // the insertelement sequence will directly follow the scalar definitions.
  2059. auto OldIP = Builder.saveIP();
  2060. auto NewIP = std::next(BasicBlock::iterator(LastInst));
  2061. Builder.SetInsertPoint(&*NewIP);
  2062. // However, if we are vectorizing, we need to construct the vector values.
  2063. // If the value is known to be uniform after vectorization, we can just
  2064. // broadcast the scalar value corresponding to lane zero for each unroll
  2065. // iteration. Otherwise, we construct the vector values using insertelement
  2066. // instructions. Since the resulting vectors are stored in
  2067. // VectorLoopValueMap, we will only generate the insertelements once.
  2068. Value *VectorValue = nullptr;
  2069. if (Cost->isUniformAfterVectorization(I, VF)) {
  2070. VectorValue = getBroadcastInstrs(ScalarValue);
  2071. VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
  2072. } else {
  2073. // Initialize packing with insertelements to start from poison.
  2074. assert(!VF.isScalable() && "VF is assumed to be non scalable.");
  2075. Value *Poison = PoisonValue::get(VectorType::get(V->getType(), VF));
  2076. VectorLoopValueMap.setVectorValue(V, Part, Poison);
  2077. for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
  2078. packScalarIntoVectorValue(V, {Part, Lane});
  2079. VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
  2080. }
  2081. Builder.restoreIP(OldIP);
  2082. return VectorValue;
  2083. }
  2084. // If this scalar is unknown, assume that it is a constant or that it is
  2085. // loop invariant. Broadcast V and save the value for future uses.
  2086. Value *B = getBroadcastInstrs(V);
  2087. VectorLoopValueMap.setVectorValue(V, Part, B);
  2088. return B;
  2089. }
  2090. Value *
  2091. InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
  2092. const VPIteration &Instance) {
  2093. // If the value is not an instruction contained in the loop, it should
  2094. // already be scalar.
  2095. if (OrigLoop->isLoopInvariant(V))
  2096. return V;
  2097. assert(Instance.Lane > 0
  2098. ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
  2099. : true && "Uniform values only have lane zero");
  2100. // If the value from the original loop has not been vectorized, it is
  2101. // represented by UF x VF scalar values in the new loop. Return the requested
  2102. // scalar value.
  2103. if (VectorLoopValueMap.hasScalarValue(V, Instance))
  2104. return VectorLoopValueMap.getScalarValue(V, Instance);
  2105. // If the value has not been scalarized, get its entry in VectorLoopValueMap
  2106. // for the given unroll part. If this entry is not a vector type (i.e., the
  2107. // vectorization factor is one), there is no need to generate an
  2108. // extractelement instruction.
  2109. auto *U = getOrCreateVectorValue(V, Instance.Part);
  2110. if (!U->getType()->isVectorTy()) {
  2111. assert(VF.isScalar() && "Value not scalarized has non-vector type");
  2112. return U;
  2113. }
  2114. // Otherwise, the value from the original loop has been vectorized and is
  2115. // represented by UF vector values. Extract and return the requested scalar
  2116. // value from the appropriate vector lane.
  2117. return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
  2118. }
  2119. void InnerLoopVectorizer::packScalarIntoVectorValue(
  2120. Value *V, const VPIteration &Instance) {
  2121. assert(V != Induction && "The new induction variable should not be used.");
  2122. assert(!V->getType()->isVectorTy() && "Can't pack a vector");
  2123. assert(!V->getType()->isVoidTy() && "Type does not produce a value");
  2124. Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
  2125. Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
  2126. VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
  2127. Builder.getInt32(Instance.Lane));
  2128. VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
  2129. }
  2130. Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
  2131. assert(Vec->getType()->isVectorTy() && "Invalid type");
  2132. assert(!VF.isScalable() && "Cannot reverse scalable vectors");
  2133. SmallVector<int, 8> ShuffleMask;
  2134. for (unsigned i = 0; i < VF.getKnownMinValue(); ++i)
  2135. ShuffleMask.push_back(VF.getKnownMinValue() - i - 1);
  2136. return Builder.CreateShuffleVector(Vec, ShuffleMask, "reverse");
  2137. }
  2138. // Return whether we allow using masked interleave-groups (for dealing with
  2139. // strided loads/stores that reside in predicated blocks, or for dealing
  2140. // with gaps).
  2141. static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
  2142. // If an override option has been passed in for interleaved accesses, use it.
  2143. if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
  2144. return EnableMaskedInterleavedMemAccesses;
  2145. return TTI.enableMaskedInterleavedAccessVectorization();
  2146. }
  2147. // Try to vectorize the interleave group that \p Instr belongs to.
  2148. //
  2149. // E.g. Translate following interleaved load group (factor = 3):
  2150. // for (i = 0; i < N; i+=3) {
  2151. // R = Pic[i]; // Member of index 0
  2152. // G = Pic[i+1]; // Member of index 1
  2153. // B = Pic[i+2]; // Member of index 2
  2154. // ... // do something to R, G, B
  2155. // }
  2156. // To:
  2157. // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
  2158. // %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
  2159. // %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
  2160. // %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
  2161. //
  2162. // Or translate following interleaved store group (factor = 3):
  2163. // for (i = 0; i < N; i+=3) {
  2164. // ... do something to R, G, B
  2165. // Pic[i] = R; // Member of index 0
  2166. // Pic[i+1] = G; // Member of index 1
  2167. // Pic[i+2] = B; // Member of index 2
  2168. // }
  2169. // To:
  2170. // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
  2171. // %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
  2172. // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
  2173. // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
  2174. // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
  2175. void InnerLoopVectorizer::vectorizeInterleaveGroup(
  2176. const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
  2177. VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
  2178. VPValue *BlockInMask) {
  2179. Instruction *Instr = Group->getInsertPos();
  2180. const DataLayout &DL = Instr->getModule()->getDataLayout();
  2181. // Prepare for the vector type of the interleaved load/store.
  2182. Type *ScalarTy = getMemInstValueType(Instr);
  2183. unsigned InterleaveFactor = Group->getFactor();
  2184. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  2185. auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
  2186. // Prepare for the new pointers.
  2187. SmallVector<Value *, 2> AddrParts;
  2188. unsigned Index = Group->getIndex(Instr);
  2189. // TODO: extend the masked interleaved-group support to reversed access.
  2190. assert((!BlockInMask || !Group->isReverse()) &&
  2191. "Reversed masked interleave-group not supported.");
  2192. // If the group is reverse, adjust the index to refer to the last vector lane
  2193. // instead of the first. We adjust the index from the first vector lane,
  2194. // rather than directly getting the pointer for lane VF - 1, because the
  2195. // pointer operand of the interleaved access is supposed to be uniform. For
  2196. // uniform instructions, we're only required to generate a value for the
  2197. // first vector lane in each unroll iteration.
  2198. assert(!VF.isScalable() &&
  2199. "scalable vector reverse operation is not implemented");
  2200. if (Group->isReverse())
  2201. Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
  2202. for (unsigned Part = 0; Part < UF; Part++) {
  2203. Value *AddrPart = State.get(Addr, {Part, 0});
  2204. setDebugLocFromInst(Builder, AddrPart);
  2205. // Notice current instruction could be any index. Need to adjust the address
  2206. // to the member of index 0.
  2207. //
  2208. // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
  2209. // b = A[i]; // Member of index 0
  2210. // Current pointer is pointed to A[i+1], adjust it to A[i].
  2211. //
  2212. // E.g. A[i+1] = a; // Member of index 1
  2213. // A[i] = b; // Member of index 0
  2214. // A[i+2] = c; // Member of index 2 (Current instruction)
  2215. // Current pointer is pointed to A[i+2], adjust it to A[i].
  2216. bool InBounds = false;
  2217. if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
  2218. InBounds = gep->isInBounds();
  2219. AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
  2220. cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
  2221. // Cast to the vector pointer type.
  2222. unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
  2223. Type *PtrTy = VecTy->getPointerTo(AddressSpace);
  2224. AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
  2225. }
  2226. setDebugLocFromInst(Builder, Instr);
  2227. Value *PoisonVec = PoisonValue::get(VecTy);
  2228. Value *MaskForGaps = nullptr;
  2229. if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
  2230. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  2231. MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
  2232. assert(MaskForGaps && "Mask for Gaps is required but it is null");
  2233. }
  2234. // Vectorize the interleaved load group.
  2235. if (isa<LoadInst>(Instr)) {
  2236. // For each unroll part, create a wide load for the group.
  2237. SmallVector<Value *, 2> NewLoads;
  2238. for (unsigned Part = 0; Part < UF; Part++) {
  2239. Instruction *NewLoad;
  2240. if (BlockInMask || MaskForGaps) {
  2241. assert(useMaskedInterleavedAccesses(*TTI) &&
  2242. "masked interleaved groups are not allowed.");
  2243. Value *GroupMask = MaskForGaps;
  2244. if (BlockInMask) {
  2245. Value *BlockInMaskPart = State.get(BlockInMask, Part);
  2246. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  2247. Value *ShuffledMask = Builder.CreateShuffleVector(
  2248. BlockInMaskPart,
  2249. createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
  2250. "interleaved.mask");
  2251. GroupMask = MaskForGaps
  2252. ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
  2253. MaskForGaps)
  2254. : ShuffledMask;
  2255. }
  2256. NewLoad =
  2257. Builder.CreateMaskedLoad(AddrParts[Part], Group->getAlign(),
  2258. GroupMask, PoisonVec, "wide.masked.vec");
  2259. }
  2260. else
  2261. NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
  2262. Group->getAlign(), "wide.vec");
  2263. Group->addMetadata(NewLoad);
  2264. NewLoads.push_back(NewLoad);
  2265. }
  2266. // For each member in the group, shuffle out the appropriate data from the
  2267. // wide loads.
  2268. unsigned J = 0;
  2269. for (unsigned I = 0; I < InterleaveFactor; ++I) {
  2270. Instruction *Member = Group->getMember(I);
  2271. // Skip the gaps in the group.
  2272. if (!Member)
  2273. continue;
  2274. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  2275. auto StrideMask =
  2276. createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
  2277. for (unsigned Part = 0; Part < UF; Part++) {
  2278. Value *StridedVec = Builder.CreateShuffleVector(
  2279. NewLoads[Part], StrideMask, "strided.vec");
  2280. // If this member has different type, cast the result type.
  2281. if (Member->getType() != ScalarTy) {
  2282. assert(!VF.isScalable() && "VF is assumed to be non scalable.");
  2283. VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
  2284. StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
  2285. }
  2286. if (Group->isReverse())
  2287. StridedVec = reverseVector(StridedVec);
  2288. State.set(VPDefs[J], Member, StridedVec, Part);
  2289. }
  2290. ++J;
  2291. }
  2292. return;
  2293. }
  2294. // The sub vector type for current instruction.
  2295. assert(!VF.isScalable() && "VF is assumed to be non scalable.");
  2296. auto *SubVT = VectorType::get(ScalarTy, VF);
  2297. // Vectorize the interleaved store group.
  2298. for (unsigned Part = 0; Part < UF; Part++) {
  2299. // Collect the stored vector from each member.
  2300. SmallVector<Value *, 4> StoredVecs;
  2301. for (unsigned i = 0; i < InterleaveFactor; i++) {
  2302. // Interleaved store group doesn't allow a gap, so each index has a member
  2303. assert(Group->getMember(i) && "Fail to get a member from an interleaved store group");
  2304. Value *StoredVec = State.get(StoredValues[i], Part);
  2305. if (Group->isReverse())
  2306. StoredVec = reverseVector(StoredVec);
  2307. // If this member has different type, cast it to a unified type.
  2308. if (StoredVec->getType() != SubVT)
  2309. StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
  2310. StoredVecs.push_back(StoredVec);
  2311. }
  2312. // Concatenate all vectors into a wide vector.
  2313. Value *WideVec = concatenateVectors(Builder, StoredVecs);
  2314. // Interleave the elements in the wide vector.
  2315. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  2316. Value *IVec = Builder.CreateShuffleVector(
  2317. WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
  2318. "interleaved.vec");
  2319. Instruction *NewStoreInstr;
  2320. if (BlockInMask) {
  2321. Value *BlockInMaskPart = State.get(BlockInMask, Part);
  2322. Value *ShuffledMask = Builder.CreateShuffleVector(
  2323. BlockInMaskPart,
  2324. createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
  2325. "interleaved.mask");
  2326. NewStoreInstr = Builder.CreateMaskedStore(
  2327. IVec, AddrParts[Part], Group->getAlign(), ShuffledMask);
  2328. }
  2329. else
  2330. NewStoreInstr =
  2331. Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
  2332. Group->addMetadata(NewStoreInstr);
  2333. }
  2334. }
  2335. void InnerLoopVectorizer::vectorizeMemoryInstruction(
  2336. Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
  2337. VPValue *StoredValue, VPValue *BlockInMask) {
  2338. // Attempt to issue a wide load.
  2339. LoadInst *LI = dyn_cast<LoadInst>(Instr);
  2340. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  2341. assert((LI || SI) && "Invalid Load/Store instruction");
  2342. assert((!SI || StoredValue) && "No stored value provided for widened store");
  2343. assert((!LI || !StoredValue) && "Stored value provided for widened load");
  2344. LoopVectorizationCostModel::InstWidening Decision =
  2345. Cost->getWideningDecision(Instr, VF);
  2346. assert((Decision == LoopVectorizationCostModel::CM_Widen ||
  2347. Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
  2348. Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
  2349. "CM decision is not to widen the memory instruction");
  2350. Type *ScalarDataTy = getMemInstValueType(Instr);
  2351. auto *DataTy = VectorType::get(ScalarDataTy, VF);
  2352. const Align Alignment = getLoadStoreAlignment(Instr);
  2353. // Determine if the pointer operand of the access is either consecutive or
  2354. // reverse consecutive.
  2355. bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
  2356. bool ConsecutiveStride =
  2357. Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
  2358. bool CreateGatherScatter =
  2359. (Decision == LoopVectorizationCostModel::CM_GatherScatter);
  2360. // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
  2361. // gather/scatter. Otherwise Decision should have been to Scalarize.
  2362. assert((ConsecutiveStride || CreateGatherScatter) &&
  2363. "The instruction should be scalarized");
  2364. (void)ConsecutiveStride;
  2365. VectorParts BlockInMaskParts(UF);
  2366. bool isMaskRequired = BlockInMask;
  2367. if (isMaskRequired)
  2368. for (unsigned Part = 0; Part < UF; ++Part)
  2369. BlockInMaskParts[Part] = State.get(BlockInMask, Part);
  2370. const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
  2371. // Calculate the pointer for the specific unroll-part.
  2372. GetElementPtrInst *PartPtr = nullptr;
  2373. bool InBounds = false;
  2374. if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
  2375. InBounds = gep->isInBounds();
  2376. if (Reverse) {
  2377. assert(!VF.isScalable() &&
  2378. "Reversing vectors is not yet supported for scalable vectors.");
  2379. // If the address is consecutive but reversed, then the
  2380. // wide store needs to start at the last vector element.
  2381. PartPtr = cast<GetElementPtrInst>(Builder.CreateGEP(
  2382. ScalarDataTy, Ptr, Builder.getInt32(-Part * VF.getKnownMinValue())));
  2383. PartPtr->setIsInBounds(InBounds);
  2384. PartPtr = cast<GetElementPtrInst>(Builder.CreateGEP(
  2385. ScalarDataTy, PartPtr, Builder.getInt32(1 - VF.getKnownMinValue())));
  2386. PartPtr->setIsInBounds(InBounds);
  2387. if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
  2388. BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
  2389. } else {
  2390. Value *Increment = createStepForVF(Builder, Builder.getInt32(Part), VF);
  2391. PartPtr = cast<GetElementPtrInst>(
  2392. Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
  2393. PartPtr->setIsInBounds(InBounds);
  2394. }
  2395. unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
  2396. return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
  2397. };
  2398. // Handle Stores:
  2399. if (SI) {
  2400. setDebugLocFromInst(Builder, SI);
  2401. for (unsigned Part = 0; Part < UF; ++Part) {
  2402. Instruction *NewSI = nullptr;
  2403. Value *StoredVal = State.get(StoredValue, Part);
  2404. if (CreateGatherScatter) {
  2405. Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
  2406. Value *VectorGep = State.get(Addr, Part);
  2407. NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
  2408. MaskPart);
  2409. } else {
  2410. if (Reverse) {
  2411. // If we store to reverse consecutive memory locations, then we need
  2412. // to reverse the order of elements in the stored value.
  2413. StoredVal = reverseVector(StoredVal);
  2414. // We don't want to update the value in the map as it might be used in
  2415. // another expression. So don't call resetVectorValue(StoredVal).
  2416. }
  2417. auto *VecPtr = CreateVecPtr(Part, State.get(Addr, {0, 0}));
  2418. if (isMaskRequired)
  2419. NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
  2420. BlockInMaskParts[Part]);
  2421. else
  2422. NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
  2423. }
  2424. addMetadata(NewSI, SI);
  2425. }
  2426. return;
  2427. }
  2428. // Handle loads.
  2429. assert(LI && "Must have a load instruction");
  2430. setDebugLocFromInst(Builder, LI);
  2431. for (unsigned Part = 0; Part < UF; ++Part) {
  2432. Value *NewLI;
  2433. if (CreateGatherScatter) {
  2434. Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
  2435. Value *VectorGep = State.get(Addr, Part);
  2436. NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
  2437. nullptr, "wide.masked.gather");
  2438. addMetadata(NewLI, LI);
  2439. } else {
  2440. auto *VecPtr = CreateVecPtr(Part, State.get(Addr, {0, 0}));
  2441. if (isMaskRequired)
  2442. NewLI = Builder.CreateMaskedLoad(
  2443. VecPtr, Alignment, BlockInMaskParts[Part], PoisonValue::get(DataTy),
  2444. "wide.masked.load");
  2445. else
  2446. NewLI =
  2447. Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
  2448. // Add metadata to the load, but setVectorValue to the reverse shuffle.
  2449. addMetadata(NewLI, LI);
  2450. if (Reverse)
  2451. NewLI = reverseVector(NewLI);
  2452. }
  2453. State.set(Def, Instr, NewLI, Part);
  2454. }
  2455. }
  2456. void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPUser &User,
  2457. const VPIteration &Instance,
  2458. bool IfPredicateInstr,
  2459. VPTransformState &State) {
  2460. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  2461. // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
  2462. // the first lane and part.
  2463. if (isa<NoAliasScopeDeclInst>(Instr))
  2464. if (Instance.Lane != 0 || Instance.Part != 0)
  2465. return;
  2466. setDebugLocFromInst(Builder, Instr);
  2467. // Does this instruction return a value ?
  2468. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  2469. Instruction *Cloned = Instr->clone();
  2470. if (!IsVoidRetTy)
  2471. Cloned->setName(Instr->getName() + ".cloned");
  2472. // Replace the operands of the cloned instructions with their scalar
  2473. // equivalents in the new loop.
  2474. for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
  2475. auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
  2476. auto InputInstance = Instance;
  2477. if (!Operand || !OrigLoop->contains(Operand) ||
  2478. (Cost->isUniformAfterVectorization(Operand, State.VF)))
  2479. InputInstance.Lane = 0;
  2480. auto *NewOp = State.get(User.getOperand(op), InputInstance);
  2481. Cloned->setOperand(op, NewOp);
  2482. }
  2483. addNewMetadata(Cloned, Instr);
  2484. // Place the cloned scalar in the new loop.
  2485. Builder.Insert(Cloned);
  2486. // TODO: Set result for VPValue of VPReciplicateRecipe. This requires
  2487. // representing scalar values in VPTransformState. Add the cloned scalar to
  2488. // the scalar map entry.
  2489. VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
  2490. // If we just cloned a new assumption, add it the assumption cache.
  2491. if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
  2492. if (II->getIntrinsicID() == Intrinsic::assume)
  2493. AC->registerAssumption(II);
  2494. // End if-block.
  2495. if (IfPredicateInstr)
  2496. PredicatedInstructions.push_back(Cloned);
  2497. }
  2498. PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
  2499. Value *End, Value *Step,
  2500. Instruction *DL) {
  2501. BasicBlock *Header = L->getHeader();
  2502. BasicBlock *Latch = L->getLoopLatch();
  2503. // As we're just creating this loop, it's possible no latch exists
  2504. // yet. If so, use the header as this will be a single block loop.
  2505. if (!Latch)
  2506. Latch = Header;
  2507. IRBuilder<> Builder(&*Header->getFirstInsertionPt());
  2508. Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
  2509. setDebugLocFromInst(Builder, OldInst);
  2510. auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
  2511. Builder.SetInsertPoint(Latch->getTerminator());
  2512. setDebugLocFromInst(Builder, OldInst);
  2513. // Create i+1 and fill the PHINode.
  2514. Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
  2515. Induction->addIncoming(Start, L->getLoopPreheader());
  2516. Induction->addIncoming(Next, Latch);
  2517. // Create the compare.
  2518. Value *ICmp = Builder.CreateICmpEQ(Next, End);
  2519. Builder.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
  2520. // Now we have two terminators. Remove the old one from the block.
  2521. Latch->getTerminator()->eraseFromParent();
  2522. return Induction;
  2523. }
  2524. Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
  2525. if (TripCount)
  2526. return TripCount;
  2527. assert(L && "Create Trip Count for null loop.");
  2528. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2529. // Find the loop boundaries.
  2530. ScalarEvolution *SE = PSE.getSE();
  2531. const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
  2532. assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
  2533. "Invalid loop count");
  2534. Type *IdxTy = Legal->getWidestInductionType();
  2535. assert(IdxTy && "No type for induction");
  2536. // The exit count might have the type of i64 while the phi is i32. This can
  2537. // happen if we have an induction variable that is sign extended before the
  2538. // compare. The only way that we get a backedge taken count is that the
  2539. // induction variable was signed and as such will not overflow. In such a case
  2540. // truncation is legal.
  2541. if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
  2542. IdxTy->getPrimitiveSizeInBits())
  2543. BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
  2544. BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
  2545. // Get the total trip count from the count by adding 1.
  2546. const SCEV *ExitCount = SE->getAddExpr(
  2547. BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
  2548. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  2549. // Expand the trip count and place the new instructions in the preheader.
  2550. // Notice that the pre-header does not change, only the loop body.
  2551. SCEVExpander Exp(*SE, DL, "induction");
  2552. // Count holds the overall loop count (N).
  2553. TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
  2554. L->getLoopPreheader()->getTerminator());
  2555. if (TripCount->getType()->isPointerTy())
  2556. TripCount =
  2557. CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
  2558. L->getLoopPreheader()->getTerminator());
  2559. return TripCount;
  2560. }
  2561. Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
  2562. if (VectorTripCount)
  2563. return VectorTripCount;
  2564. Value *TC = getOrCreateTripCount(L);
  2565. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2566. Type *Ty = TC->getType();
  2567. // This is where we can make the step a runtime constant.
  2568. Value *Step = createStepForVF(Builder, ConstantInt::get(Ty, UF), VF);
  2569. // If the tail is to be folded by masking, round the number of iterations N
  2570. // up to a multiple of Step instead of rounding down. This is done by first
  2571. // adding Step-1 and then rounding down. Note that it's ok if this addition
  2572. // overflows: the vector induction variable will eventually wrap to zero given
  2573. // that it starts at zero and its Step is a power of two; the loop will then
  2574. // exit, with the last early-exit vector comparison also producing all-true.
  2575. if (Cost->foldTailByMasking()) {
  2576. assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
  2577. "VF*UF must be a power of 2 when folding tail by masking");
  2578. assert(!VF.isScalable() &&
  2579. "Tail folding not yet supported for scalable vectors");
  2580. TC = Builder.CreateAdd(
  2581. TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
  2582. }
  2583. // Now we need to generate the expression for the part of the loop that the
  2584. // vectorized body will execute. This is equal to N - (N % Step) if scalar
  2585. // iterations are not required for correctness, or N - Step, otherwise. Step
  2586. // is equal to the vectorization factor (number of SIMD elements) times the
  2587. // unroll factor (number of SIMD instructions).
  2588. Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
  2589. // There are two cases where we need to ensure (at least) the last iteration
  2590. // runs in the scalar remainder loop. Thus, if the step evenly divides
  2591. // the trip count, we set the remainder to be equal to the step. If the step
  2592. // does not evenly divide the trip count, no adjustment is necessary since
  2593. // there will already be scalar iterations. Note that the minimum iterations
  2594. // check ensures that N >= Step. The cases are:
  2595. // 1) If there is a non-reversed interleaved group that may speculatively
  2596. // access memory out-of-bounds.
  2597. // 2) If any instruction may follow a conditionally taken exit. That is, if
  2598. // the loop contains multiple exiting blocks, or a single exiting block
  2599. // which is not the latch.
  2600. if (VF.isVector() && Cost->requiresScalarEpilogue()) {
  2601. auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
  2602. R = Builder.CreateSelect(IsZero, Step, R);
  2603. }
  2604. VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
  2605. return VectorTripCount;
  2606. }
  2607. Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
  2608. const DataLayout &DL) {
  2609. // Verify that V is a vector type with same number of elements as DstVTy.
  2610. auto *DstFVTy = cast<FixedVectorType>(DstVTy);
  2611. unsigned VF = DstFVTy->getNumElements();
  2612. auto *SrcVecTy = cast<FixedVectorType>(V->getType());
  2613. assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
  2614. Type *SrcElemTy = SrcVecTy->getElementType();
  2615. Type *DstElemTy = DstFVTy->getElementType();
  2616. assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
  2617. "Vector elements must have same size");
  2618. // Do a direct cast if element types are castable.
  2619. if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
  2620. return Builder.CreateBitOrPointerCast(V, DstFVTy);
  2621. }
  2622. // V cannot be directly casted to desired vector type.
  2623. // May happen when V is a floating point vector but DstVTy is a vector of
  2624. // pointers or vice-versa. Handle this using a two-step bitcast using an
  2625. // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
  2626. assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
  2627. "Only one type should be a pointer type");
  2628. assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
  2629. "Only one type should be a floating point type");
  2630. Type *IntTy =
  2631. IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
  2632. auto *VecIntTy = FixedVectorType::get(IntTy, VF);
  2633. Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
  2634. return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
  2635. }
  2636. void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
  2637. BasicBlock *Bypass) {
  2638. Value *Count = getOrCreateTripCount(L);
  2639. // Reuse existing vector loop preheader for TC checks.
  2640. // Note that new preheader block is generated for vector loop.
  2641. BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
  2642. IRBuilder<> Builder(TCCheckBlock->getTerminator());
  2643. // Generate code to check if the loop's trip count is less than VF * UF, or
  2644. // equal to it in case a scalar epilogue is required; this implies that the
  2645. // vector trip count is zero. This check also covers the case where adding one
  2646. // to the backedge-taken count overflowed leading to an incorrect trip count
  2647. // of zero. In this case we will also jump to the scalar loop.
  2648. auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
  2649. : ICmpInst::ICMP_ULT;
  2650. // If tail is to be folded, vector loop takes care of all iterations.
  2651. Value *CheckMinIters = Builder.getFalse();
  2652. if (!Cost->foldTailByMasking()) {
  2653. Value *Step =
  2654. createStepForVF(Builder, ConstantInt::get(Count->getType(), UF), VF);
  2655. CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
  2656. }
  2657. // Create new preheader for vector loop.
  2658. LoopVectorPreHeader =
  2659. SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
  2660. "vector.ph");
  2661. assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
  2662. DT->getNode(Bypass)->getIDom()) &&
  2663. "TC check is expected to dominate Bypass");
  2664. // Update dominator for Bypass & LoopExit.
  2665. DT->changeImmediateDominator(Bypass, TCCheckBlock);
  2666. DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
  2667. ReplaceInstWithInst(
  2668. TCCheckBlock->getTerminator(),
  2669. BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
  2670. LoopBypassBlocks.push_back(TCCheckBlock);
  2671. }
  2672. void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
  2673. // Reuse existing vector loop preheader for SCEV checks.
  2674. // Note that new preheader block is generated for vector loop.
  2675. BasicBlock *const SCEVCheckBlock = LoopVectorPreHeader;
  2676. // Generate the code to check that the SCEV assumptions that we made.
  2677. // We want the new basic block to start at the first instruction in a
  2678. // sequence of instructions that form a check.
  2679. SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
  2680. "scev.check");
  2681. Value *SCEVCheck = Exp.expandCodeForPredicate(
  2682. &PSE.getUnionPredicate(), SCEVCheckBlock->getTerminator());
  2683. if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
  2684. if (C->isZero())
  2685. return;
  2686. assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
  2687. (OptForSizeBasedOnProfile &&
  2688. Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
  2689. "Cannot SCEV check stride or overflow when optimizing for size");
  2690. SCEVCheckBlock->setName("vector.scevcheck");
  2691. // Create new preheader for vector loop.
  2692. LoopVectorPreHeader =
  2693. SplitBlock(SCEVCheckBlock, SCEVCheckBlock->getTerminator(), DT, LI,
  2694. nullptr, "vector.ph");
  2695. // Update dominator only if this is first RT check.
  2696. if (LoopBypassBlocks.empty()) {
  2697. DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
  2698. DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
  2699. }
  2700. ReplaceInstWithInst(
  2701. SCEVCheckBlock->getTerminator(),
  2702. BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheck));
  2703. LoopBypassBlocks.push_back(SCEVCheckBlock);
  2704. AddedSafetyChecks = true;
  2705. }
  2706. void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
  2707. // VPlan-native path does not do any analysis for runtime checks currently.
  2708. if (EnableVPlanNativePath)
  2709. return;
  2710. // Reuse existing vector loop preheader for runtime memory checks.
  2711. // Note that new preheader block is generated for vector loop.
  2712. BasicBlock *const MemCheckBlock = L->getLoopPreheader();
  2713. // Generate the code that checks in runtime if arrays overlap. We put the
  2714. // checks into a separate block to make the more common case of few elements
  2715. // faster.
  2716. auto *LAI = Legal->getLAI();
  2717. const auto &RtPtrChecking = *LAI->getRuntimePointerChecking();
  2718. if (!RtPtrChecking.Need)
  2719. return;
  2720. if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
  2721. assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
  2722. "Cannot emit memory checks when optimizing for size, unless forced "
  2723. "to vectorize.");
  2724. ORE->emit([&]() {
  2725. return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
  2726. L->getStartLoc(), L->getHeader())
  2727. << "Code-size may be reduced by not forcing "
  2728. "vectorization, or by source-code modifications "
  2729. "eliminating the need for runtime checks "
  2730. "(e.g., adding 'restrict').";
  2731. });
  2732. }
  2733. MemCheckBlock->setName("vector.memcheck");
  2734. // Create new preheader for vector loop.
  2735. LoopVectorPreHeader =
  2736. SplitBlock(MemCheckBlock, MemCheckBlock->getTerminator(), DT, LI, nullptr,
  2737. "vector.ph");
  2738. auto *CondBranch = cast<BranchInst>(
  2739. Builder.CreateCondBr(Builder.getTrue(), Bypass, LoopVectorPreHeader));
  2740. ReplaceInstWithInst(MemCheckBlock->getTerminator(), CondBranch);
  2741. LoopBypassBlocks.push_back(MemCheckBlock);
  2742. AddedSafetyChecks = true;
  2743. // Update dominator only if this is first RT check.
  2744. if (LoopBypassBlocks.empty()) {
  2745. DT->changeImmediateDominator(Bypass, MemCheckBlock);
  2746. DT->changeImmediateDominator(LoopExitBlock, MemCheckBlock);
  2747. }
  2748. Instruction *FirstCheckInst;
  2749. Instruction *MemRuntimeCheck;
  2750. std::tie(FirstCheckInst, MemRuntimeCheck) =
  2751. addRuntimeChecks(MemCheckBlock->getTerminator(), OrigLoop,
  2752. RtPtrChecking.getChecks(), RtPtrChecking.getSE());
  2753. assert(MemRuntimeCheck && "no RT checks generated although RtPtrChecking "
  2754. "claimed checks are required");
  2755. CondBranch->setCondition(MemRuntimeCheck);
  2756. // We currently don't use LoopVersioning for the actual loop cloning but we
  2757. // still use it to add the noalias metadata.
  2758. LVer = std::make_unique<LoopVersioning>(
  2759. *Legal->getLAI(),
  2760. Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
  2761. DT, PSE.getSE());
  2762. LVer->prepareNoAliasMetadata();
  2763. }
  2764. Value *InnerLoopVectorizer::emitTransformedIndex(
  2765. IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
  2766. const InductionDescriptor &ID) const {
  2767. SCEVExpander Exp(*SE, DL, "induction");
  2768. auto Step = ID.getStep();
  2769. auto StartValue = ID.getStartValue();
  2770. assert(Index->getType() == Step->getType() &&
  2771. "Index type does not match StepValue type");
  2772. // Note: the IR at this point is broken. We cannot use SE to create any new
  2773. // SCEV and then expand it, hoping that SCEV's simplification will give us
  2774. // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
  2775. // lead to various SCEV crashes. So all we can do is to use builder and rely
  2776. // on InstCombine for future simplifications. Here we handle some trivial
  2777. // cases only.
  2778. auto CreateAdd = [&B](Value *X, Value *Y) {
  2779. assert(X->getType() == Y->getType() && "Types don't match!");
  2780. if (auto *CX = dyn_cast<ConstantInt>(X))
  2781. if (CX->isZero())
  2782. return Y;
  2783. if (auto *CY = dyn_cast<ConstantInt>(Y))
  2784. if (CY->isZero())
  2785. return X;
  2786. return B.CreateAdd(X, Y);
  2787. };
  2788. auto CreateMul = [&B](Value *X, Value *Y) {
  2789. assert(X->getType() == Y->getType() && "Types don't match!");
  2790. if (auto *CX = dyn_cast<ConstantInt>(X))
  2791. if (CX->isOne())
  2792. return Y;
  2793. if (auto *CY = dyn_cast<ConstantInt>(Y))
  2794. if (CY->isOne())
  2795. return X;
  2796. return B.CreateMul(X, Y);
  2797. };
  2798. // Get a suitable insert point for SCEV expansion. For blocks in the vector
  2799. // loop, choose the end of the vector loop header (=LoopVectorBody), because
  2800. // the DomTree is not kept up-to-date for additional blocks generated in the
  2801. // vector loop. By using the header as insertion point, we guarantee that the
  2802. // expanded instructions dominate all their uses.
  2803. auto GetInsertPoint = [this, &B]() {
  2804. BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
  2805. if (InsertBB != LoopVectorBody &&
  2806. LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
  2807. return LoopVectorBody->getTerminator();
  2808. return &*B.GetInsertPoint();
  2809. };
  2810. switch (ID.getKind()) {
  2811. case InductionDescriptor::IK_IntInduction: {
  2812. assert(Index->getType() == StartValue->getType() &&
  2813. "Index type does not match StartValue type");
  2814. if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
  2815. return B.CreateSub(StartValue, Index);
  2816. auto *Offset = CreateMul(
  2817. Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
  2818. return CreateAdd(StartValue, Offset);
  2819. }
  2820. case InductionDescriptor::IK_PtrInduction: {
  2821. assert(isa<SCEVConstant>(Step) &&
  2822. "Expected constant step for pointer induction");
  2823. return B.CreateGEP(
  2824. StartValue->getType()->getPointerElementType(), StartValue,
  2825. CreateMul(Index,
  2826. Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint())));
  2827. }
  2828. case InductionDescriptor::IK_FpInduction: {
  2829. assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
  2830. auto InductionBinOp = ID.getInductionBinOp();
  2831. assert(InductionBinOp &&
  2832. (InductionBinOp->getOpcode() == Instruction::FAdd ||
  2833. InductionBinOp->getOpcode() == Instruction::FSub) &&
  2834. "Original bin op should be defined for FP induction");
  2835. Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
  2836. // Floating point operations had to be 'fast' to enable the induction.
  2837. FastMathFlags Flags;
  2838. Flags.setFast();
  2839. Value *MulExp = B.CreateFMul(StepValue, Index);
  2840. if (isa<Instruction>(MulExp))
  2841. // We have to check, the MulExp may be a constant.
  2842. cast<Instruction>(MulExp)->setFastMathFlags(Flags);
  2843. Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
  2844. "induction");
  2845. if (isa<Instruction>(BOp))
  2846. cast<Instruction>(BOp)->setFastMathFlags(Flags);
  2847. return BOp;
  2848. }
  2849. case InductionDescriptor::IK_NoInduction:
  2850. return nullptr;
  2851. }
  2852. llvm_unreachable("invalid enum");
  2853. }
  2854. Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
  2855. LoopScalarBody = OrigLoop->getHeader();
  2856. LoopVectorPreHeader = OrigLoop->getLoopPreheader();
  2857. LoopExitBlock = OrigLoop->getUniqueExitBlock();
  2858. assert(LoopExitBlock && "Must have an exit block");
  2859. assert(LoopVectorPreHeader && "Invalid loop structure");
  2860. LoopMiddleBlock =
  2861. SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
  2862. LI, nullptr, Twine(Prefix) + "middle.block");
  2863. LoopScalarPreHeader =
  2864. SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
  2865. nullptr, Twine(Prefix) + "scalar.ph");
  2866. // Set up branch from middle block to the exit and scalar preheader blocks.
  2867. // completeLoopSkeleton will update the condition to use an iteration check,
  2868. // if required to decide whether to execute the remainder.
  2869. BranchInst *BrInst =
  2870. BranchInst::Create(LoopExitBlock, LoopScalarPreHeader, Builder.getTrue());
  2871. auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
  2872. BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
  2873. ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
  2874. // We intentionally don't let SplitBlock to update LoopInfo since
  2875. // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
  2876. // LoopVectorBody is explicitly added to the correct place few lines later.
  2877. LoopVectorBody =
  2878. SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
  2879. nullptr, nullptr, Twine(Prefix) + "vector.body");
  2880. // Update dominator for loop exit.
  2881. DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
  2882. // Create and register the new vector loop.
  2883. Loop *Lp = LI->AllocateLoop();
  2884. Loop *ParentLoop = OrigLoop->getParentLoop();
  2885. // Insert the new loop into the loop nest and register the new basic blocks
  2886. // before calling any utilities such as SCEV that require valid LoopInfo.
  2887. if (ParentLoop) {
  2888. ParentLoop->addChildLoop(Lp);
  2889. } else {
  2890. LI->addTopLevelLoop(Lp);
  2891. }
  2892. Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
  2893. return Lp;
  2894. }
  2895. void InnerLoopVectorizer::createInductionResumeValues(
  2896. Loop *L, Value *VectorTripCount,
  2897. std::pair<BasicBlock *, Value *> AdditionalBypass) {
  2898. assert(VectorTripCount && L && "Expected valid arguments");
  2899. assert(((AdditionalBypass.first && AdditionalBypass.second) ||
  2900. (!AdditionalBypass.first && !AdditionalBypass.second)) &&
  2901. "Inconsistent information about additional bypass.");
  2902. // We are going to resume the execution of the scalar loop.
  2903. // Go over all of the induction variables that we found and fix the
  2904. // PHIs that are left in the scalar version of the loop.
  2905. // The starting values of PHI nodes depend on the counter of the last
  2906. // iteration in the vectorized loop.
  2907. // If we come from a bypass edge then we need to start from the original
  2908. // start value.
  2909. for (auto &InductionEntry : Legal->getInductionVars()) {
  2910. PHINode *OrigPhi = InductionEntry.first;
  2911. InductionDescriptor II = InductionEntry.second;
  2912. // Create phi nodes to merge from the backedge-taken check block.
  2913. PHINode *BCResumeVal =
  2914. PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
  2915. LoopScalarPreHeader->getTerminator());
  2916. // Copy original phi DL over to the new one.
  2917. BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
  2918. Value *&EndValue = IVEndValues[OrigPhi];
  2919. Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
  2920. if (OrigPhi == OldInduction) {
  2921. // We know what the end value is.
  2922. EndValue = VectorTripCount;
  2923. } else {
  2924. IRBuilder<> B(L->getLoopPreheader()->getTerminator());
  2925. Type *StepType = II.getStep()->getType();
  2926. Instruction::CastOps CastOp =
  2927. CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
  2928. Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
  2929. const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
  2930. EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
  2931. EndValue->setName("ind.end");
  2932. // Compute the end value for the additional bypass (if applicable).
  2933. if (AdditionalBypass.first) {
  2934. B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
  2935. CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
  2936. StepType, true);
  2937. CRD =
  2938. B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
  2939. EndValueFromAdditionalBypass =
  2940. emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
  2941. EndValueFromAdditionalBypass->setName("ind.end");
  2942. }
  2943. }
  2944. // The new PHI merges the original incoming value, in case of a bypass,
  2945. // or the value at the end of the vectorized loop.
  2946. BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
  2947. // Fix the scalar body counter (PHI node).
  2948. // The old induction's phi node in the scalar body needs the truncated
  2949. // value.
  2950. for (BasicBlock *BB : LoopBypassBlocks)
  2951. BCResumeVal->addIncoming(II.getStartValue(), BB);
  2952. if (AdditionalBypass.first)
  2953. BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
  2954. EndValueFromAdditionalBypass);
  2955. OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
  2956. }
  2957. }
  2958. BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
  2959. MDNode *OrigLoopID) {
  2960. assert(L && "Expected valid loop.");
  2961. // The trip counts should be cached by now.
  2962. Value *Count = getOrCreateTripCount(L);
  2963. Value *VectorTripCount = getOrCreateVectorTripCount(L);
  2964. auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
  2965. // Add a check in the middle block to see if we have completed
  2966. // all of the iterations in the first vector loop.
  2967. // If (N - N%VF) == N, then we *don't* need to run the remainder.
  2968. // If tail is to be folded, we know we don't need to run the remainder.
  2969. if (!Cost->foldTailByMasking()) {
  2970. Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
  2971. Count, VectorTripCount, "cmp.n",
  2972. LoopMiddleBlock->getTerminator());
  2973. // Here we use the same DebugLoc as the scalar loop latch terminator instead
  2974. // of the corresponding compare because they may have ended up with
  2975. // different line numbers and we want to avoid awkward line stepping while
  2976. // debugging. Eg. if the compare has got a line number inside the loop.
  2977. CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
  2978. cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
  2979. }
  2980. // Get ready to start creating new instructions into the vectorized body.
  2981. assert(LoopVectorPreHeader == L->getLoopPreheader() &&
  2982. "Inconsistent vector loop preheader");
  2983. Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
  2984. Optional<MDNode *> VectorizedLoopID =
  2985. makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
  2986. LLVMLoopVectorizeFollowupVectorized});
  2987. if (VectorizedLoopID.hasValue()) {
  2988. L->setLoopID(VectorizedLoopID.getValue());
  2989. // Do not setAlreadyVectorized if loop attributes have been defined
  2990. // explicitly.
  2991. return LoopVectorPreHeader;
  2992. }
  2993. // Keep all loop hints from the original loop on the vector loop (we'll
  2994. // replace the vectorizer-specific hints below).
  2995. if (MDNode *LID = OrigLoop->getLoopID())
  2996. L->setLoopID(LID);
  2997. LoopVectorizeHints Hints(L, true, *ORE);
  2998. Hints.setAlreadyVectorized();
  2999. #ifdef EXPENSIVE_CHECKS
  3000. assert(DT->verify(DominatorTree::VerificationLevel::Fast));
  3001. LI->verify(*DT);
  3002. #endif
  3003. return LoopVectorPreHeader;
  3004. }
  3005. BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
  3006. /*
  3007. In this function we generate a new loop. The new loop will contain
  3008. the vectorized instructions while the old loop will continue to run the
  3009. scalar remainder.
  3010. [ ] <-- loop iteration number check.
  3011. / |
  3012. / v
  3013. | [ ] <-- vector loop bypass (may consist of multiple blocks).
  3014. | / |
  3015. | / v
  3016. || [ ] <-- vector pre header.
  3017. |/ |
  3018. | v
  3019. | [ ] \
  3020. | [ ]_| <-- vector loop.
  3021. | |
  3022. | v
  3023. | -[ ] <--- middle-block.
  3024. | / |
  3025. | / v
  3026. -|- >[ ] <--- new preheader.
  3027. | |
  3028. | v
  3029. | [ ] \
  3030. | [ ]_| <-- old scalar loop to handle remainder.
  3031. \ |
  3032. \ v
  3033. >[ ] <-- exit block.
  3034. ...
  3035. */
  3036. // Get the metadata of the original loop before it gets modified.
  3037. MDNode *OrigLoopID = OrigLoop->getLoopID();
  3038. // Create an empty vector loop, and prepare basic blocks for the runtime
  3039. // checks.
  3040. Loop *Lp = createVectorLoopSkeleton("");
  3041. // Now, compare the new count to zero. If it is zero skip the vector loop and
  3042. // jump to the scalar loop. This check also covers the case where the
  3043. // backedge-taken count is uint##_max: adding one to it will overflow leading
  3044. // to an incorrect trip count of zero. In this (rare) case we will also jump
  3045. // to the scalar loop.
  3046. emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
  3047. // Generate the code to check any assumptions that we've made for SCEV
  3048. // expressions.
  3049. emitSCEVChecks(Lp, LoopScalarPreHeader);
  3050. // Generate the code that checks in runtime if arrays overlap. We put the
  3051. // checks into a separate block to make the more common case of few elements
  3052. // faster.
  3053. emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
  3054. // Some loops have a single integer induction variable, while other loops
  3055. // don't. One example is c++ iterators that often have multiple pointer
  3056. // induction variables. In the code below we also support a case where we
  3057. // don't have a single induction variable.
  3058. //
  3059. // We try to obtain an induction variable from the original loop as hard
  3060. // as possible. However if we don't find one that:
  3061. // - is an integer
  3062. // - counts from zero, stepping by one
  3063. // - is the size of the widest induction variable type
  3064. // then we create a new one.
  3065. OldInduction = Legal->getPrimaryInduction();
  3066. Type *IdxTy = Legal->getWidestInductionType();
  3067. Value *StartIdx = ConstantInt::get(IdxTy, 0);
  3068. // The loop step is equal to the vectorization factor (num of SIMD elements)
  3069. // times the unroll factor (num of SIMD instructions).
  3070. Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
  3071. Value *Step = createStepForVF(Builder, ConstantInt::get(IdxTy, UF), VF);
  3072. Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
  3073. Induction =
  3074. createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
  3075. getDebugLocFromInstOrOperands(OldInduction));
  3076. // Emit phis for the new starting index of the scalar loop.
  3077. createInductionResumeValues(Lp, CountRoundDown);
  3078. return completeLoopSkeleton(Lp, OrigLoopID);
  3079. }
  3080. // Fix up external users of the induction variable. At this point, we are
  3081. // in LCSSA form, with all external PHIs that use the IV having one input value,
  3082. // coming from the remainder loop. We need those PHIs to also have a correct
  3083. // value for the IV when arriving directly from the middle block.
  3084. void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
  3085. const InductionDescriptor &II,
  3086. Value *CountRoundDown, Value *EndValue,
  3087. BasicBlock *MiddleBlock) {
  3088. // There are two kinds of external IV usages - those that use the value
  3089. // computed in the last iteration (the PHI) and those that use the penultimate
  3090. // value (the value that feeds into the phi from the loop latch).
  3091. // We allow both, but they, obviously, have different values.
  3092. assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
  3093. DenseMap<Value *, Value *> MissingVals;
  3094. // An external user of the last iteration's value should see the value that
  3095. // the remainder loop uses to initialize its own IV.
  3096. Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
  3097. for (User *U : PostInc->users()) {
  3098. Instruction *UI = cast<Instruction>(U);
  3099. if (!OrigLoop->contains(UI)) {
  3100. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  3101. MissingVals[UI] = EndValue;
  3102. }
  3103. }
  3104. // An external user of the penultimate value need to see EndValue - Step.
  3105. // The simplest way to get this is to recompute it from the constituent SCEVs,
  3106. // that is Start + (Step * (CRD - 1)).
  3107. for (User *U : OrigPhi->users()) {
  3108. auto *UI = cast<Instruction>(U);
  3109. if (!OrigLoop->contains(UI)) {
  3110. const DataLayout &DL =
  3111. OrigLoop->getHeader()->getModule()->getDataLayout();
  3112. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  3113. IRBuilder<> B(MiddleBlock->getTerminator());
  3114. Value *CountMinusOne = B.CreateSub(
  3115. CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
  3116. Value *CMO =
  3117. !II.getStep()->getType()->isIntegerTy()
  3118. ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
  3119. II.getStep()->getType())
  3120. : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
  3121. CMO->setName("cast.cmo");
  3122. Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
  3123. Escape->setName("ind.escape");
  3124. MissingVals[UI] = Escape;
  3125. }
  3126. }
  3127. for (auto &I : MissingVals) {
  3128. PHINode *PHI = cast<PHINode>(I.first);
  3129. // One corner case we have to handle is two IVs "chasing" each-other,
  3130. // that is %IV2 = phi [...], [ %IV1, %latch ]
  3131. // In this case, if IV1 has an external use, we need to avoid adding both
  3132. // "last value of IV1" and "penultimate value of IV2". So, verify that we
  3133. // don't already have an incoming value for the middle block.
  3134. if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
  3135. PHI->addIncoming(I.second, MiddleBlock);
  3136. }
  3137. }
  3138. namespace {
  3139. struct CSEDenseMapInfo {
  3140. static bool canHandle(const Instruction *I) {
  3141. return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
  3142. isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
  3143. }
  3144. static inline Instruction *getEmptyKey() {
  3145. return DenseMapInfo<Instruction *>::getEmptyKey();
  3146. }
  3147. static inline Instruction *getTombstoneKey() {
  3148. return DenseMapInfo<Instruction *>::getTombstoneKey();
  3149. }
  3150. static unsigned getHashValue(const Instruction *I) {
  3151. assert(canHandle(I) && "Unknown instruction!");
  3152. return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
  3153. I->value_op_end()));
  3154. }
  3155. static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
  3156. if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
  3157. LHS == getTombstoneKey() || RHS == getTombstoneKey())
  3158. return LHS == RHS;
  3159. return LHS->isIdenticalTo(RHS);
  3160. }
  3161. };
  3162. } // end anonymous namespace
  3163. ///Perform cse of induction variable instructions.
  3164. static void cse(BasicBlock *BB) {
  3165. // Perform simple cse.
  3166. SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
  3167. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
  3168. Instruction *In = &*I++;
  3169. if (!CSEDenseMapInfo::canHandle(In))
  3170. continue;
  3171. // Check if we can replace this instruction with any of the
  3172. // visited instructions.
  3173. if (Instruction *V = CSEMap.lookup(In)) {
  3174. In->replaceAllUsesWith(V);
  3175. In->eraseFromParent();
  3176. continue;
  3177. }
  3178. CSEMap[In] = In;
  3179. }
  3180. }
  3181. InstructionCost
  3182. LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
  3183. bool &NeedToScalarize) {
  3184. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  3185. Function *F = CI->getCalledFunction();
  3186. Type *ScalarRetTy = CI->getType();
  3187. SmallVector<Type *, 4> Tys, ScalarTys;
  3188. for (auto &ArgOp : CI->arg_operands())
  3189. ScalarTys.push_back(ArgOp->getType());
  3190. // Estimate cost of scalarized vector call. The source operands are assumed
  3191. // to be vectors, so we need to extract individual elements from there,
  3192. // execute VF scalar calls, and then gather the result into the vector return
  3193. // value.
  3194. InstructionCost ScalarCallCost =
  3195. TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
  3196. if (VF.isScalar())
  3197. return ScalarCallCost;
  3198. // Compute corresponding vector type for return value and arguments.
  3199. Type *RetTy = ToVectorTy(ScalarRetTy, VF);
  3200. for (Type *ScalarTy : ScalarTys)
  3201. Tys.push_back(ToVectorTy(ScalarTy, VF));
  3202. // Compute costs of unpacking argument values for the scalar calls and
  3203. // packing the return values to a vector.
  3204. InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
  3205. InstructionCost Cost =
  3206. ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
  3207. // If we can't emit a vector call for this function, then the currently found
  3208. // cost is the cost we need to return.
  3209. NeedToScalarize = true;
  3210. VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
  3211. Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
  3212. if (!TLI || CI->isNoBuiltin() || !VecFunc)
  3213. return Cost;
  3214. // If the corresponding vector cost is cheaper, return its cost.
  3215. InstructionCost VectorCallCost =
  3216. TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
  3217. if (VectorCallCost < Cost) {
  3218. NeedToScalarize = false;
  3219. Cost = VectorCallCost;
  3220. }
  3221. return Cost;
  3222. }
  3223. InstructionCost
  3224. LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
  3225. ElementCount VF) {
  3226. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  3227. assert(ID && "Expected intrinsic call!");
  3228. IntrinsicCostAttributes CostAttrs(ID, *CI, VF);
  3229. return TTI.getIntrinsicInstrCost(CostAttrs,
  3230. TargetTransformInfo::TCK_RecipThroughput);
  3231. }
  3232. static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
  3233. auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
  3234. auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
  3235. return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
  3236. }
  3237. static Type *largestIntegerVectorType(Type *T1, Type *T2) {
  3238. auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
  3239. auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
  3240. return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
  3241. }
  3242. void InnerLoopVectorizer::truncateToMinimalBitwidths() {
  3243. // For every instruction `I` in MinBWs, truncate the operands, create a
  3244. // truncated version of `I` and reextend its result. InstCombine runs
  3245. // later and will remove any ext/trunc pairs.
  3246. SmallPtrSet<Value *, 4> Erased;
  3247. for (const auto &KV : Cost->getMinimalBitwidths()) {
  3248. // If the value wasn't vectorized, we must maintain the original scalar
  3249. // type. The absence of the value from VectorLoopValueMap indicates that it
  3250. // wasn't vectorized.
  3251. if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
  3252. continue;
  3253. for (unsigned Part = 0; Part < UF; ++Part) {
  3254. Value *I = getOrCreateVectorValue(KV.first, Part);
  3255. if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
  3256. continue;
  3257. Type *OriginalTy = I->getType();
  3258. Type *ScalarTruncatedTy =
  3259. IntegerType::get(OriginalTy->getContext(), KV.second);
  3260. auto *TruncatedTy = FixedVectorType::get(
  3261. ScalarTruncatedTy,
  3262. cast<FixedVectorType>(OriginalTy)->getNumElements());
  3263. if (TruncatedTy == OriginalTy)
  3264. continue;
  3265. IRBuilder<> B(cast<Instruction>(I));
  3266. auto ShrinkOperand = [&](Value *V) -> Value * {
  3267. if (auto *ZI = dyn_cast<ZExtInst>(V))
  3268. if (ZI->getSrcTy() == TruncatedTy)
  3269. return ZI->getOperand(0);
  3270. return B.CreateZExtOrTrunc(V, TruncatedTy);
  3271. };
  3272. // The actual instruction modification depends on the instruction type,
  3273. // unfortunately.
  3274. Value *NewI = nullptr;
  3275. if (auto *BO = dyn_cast<BinaryOperator>(I)) {
  3276. NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
  3277. ShrinkOperand(BO->getOperand(1)));
  3278. // Any wrapping introduced by shrinking this operation shouldn't be
  3279. // considered undefined behavior. So, we can't unconditionally copy
  3280. // arithmetic wrapping flags to NewI.
  3281. cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
  3282. } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
  3283. NewI =
  3284. B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
  3285. ShrinkOperand(CI->getOperand(1)));
  3286. } else if (auto *SI = dyn_cast<SelectInst>(I)) {
  3287. NewI = B.CreateSelect(SI->getCondition(),
  3288. ShrinkOperand(SI->getTrueValue()),
  3289. ShrinkOperand(SI->getFalseValue()));
  3290. } else if (auto *CI = dyn_cast<CastInst>(I)) {
  3291. switch (CI->getOpcode()) {
  3292. default:
  3293. llvm_unreachable("Unhandled cast!");
  3294. case Instruction::Trunc:
  3295. NewI = ShrinkOperand(CI->getOperand(0));
  3296. break;
  3297. case Instruction::SExt:
  3298. NewI = B.CreateSExtOrTrunc(
  3299. CI->getOperand(0),
  3300. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  3301. break;
  3302. case Instruction::ZExt:
  3303. NewI = B.CreateZExtOrTrunc(
  3304. CI->getOperand(0),
  3305. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  3306. break;
  3307. }
  3308. } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
  3309. auto Elements0 = cast<FixedVectorType>(SI->getOperand(0)->getType())
  3310. ->getNumElements();
  3311. auto *O0 = B.CreateZExtOrTrunc(
  3312. SI->getOperand(0),
  3313. FixedVectorType::get(ScalarTruncatedTy, Elements0));
  3314. auto Elements1 = cast<FixedVectorType>(SI->getOperand(1)->getType())
  3315. ->getNumElements();
  3316. auto *O1 = B.CreateZExtOrTrunc(
  3317. SI->getOperand(1),
  3318. FixedVectorType::get(ScalarTruncatedTy, Elements1));
  3319. NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
  3320. } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
  3321. // Don't do anything with the operands, just extend the result.
  3322. continue;
  3323. } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
  3324. auto Elements = cast<FixedVectorType>(IE->getOperand(0)->getType())
  3325. ->getNumElements();
  3326. auto *O0 = B.CreateZExtOrTrunc(
  3327. IE->getOperand(0),
  3328. FixedVectorType::get(ScalarTruncatedTy, Elements));
  3329. auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
  3330. NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
  3331. } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
  3332. auto Elements = cast<FixedVectorType>(EE->getOperand(0)->getType())
  3333. ->getNumElements();
  3334. auto *O0 = B.CreateZExtOrTrunc(
  3335. EE->getOperand(0),
  3336. FixedVectorType::get(ScalarTruncatedTy, Elements));
  3337. NewI = B.CreateExtractElement(O0, EE->getOperand(2));
  3338. } else {
  3339. // If we don't know what to do, be conservative and don't do anything.
  3340. continue;
  3341. }
  3342. // Lastly, extend the result.
  3343. NewI->takeName(cast<Instruction>(I));
  3344. Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
  3345. I->replaceAllUsesWith(Res);
  3346. cast<Instruction>(I)->eraseFromParent();
  3347. Erased.insert(I);
  3348. VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
  3349. }
  3350. }
  3351. // We'll have created a bunch of ZExts that are now parentless. Clean up.
  3352. for (const auto &KV : Cost->getMinimalBitwidths()) {
  3353. // If the value wasn't vectorized, we must maintain the original scalar
  3354. // type. The absence of the value from VectorLoopValueMap indicates that it
  3355. // wasn't vectorized.
  3356. if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
  3357. continue;
  3358. for (unsigned Part = 0; Part < UF; ++Part) {
  3359. Value *I = getOrCreateVectorValue(KV.first, Part);
  3360. ZExtInst *Inst = dyn_cast<ZExtInst>(I);
  3361. if (Inst && Inst->use_empty()) {
  3362. Value *NewI = Inst->getOperand(0);
  3363. Inst->eraseFromParent();
  3364. VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
  3365. }
  3366. }
  3367. }
  3368. }
  3369. void InnerLoopVectorizer::fixVectorizedLoop() {
  3370. // Insert truncates and extends for any truncated instructions as hints to
  3371. // InstCombine.
  3372. if (VF.isVector())
  3373. truncateToMinimalBitwidths();
  3374. // Fix widened non-induction PHIs by setting up the PHI operands.
  3375. if (OrigPHIsToFix.size()) {
  3376. assert(EnableVPlanNativePath &&
  3377. "Unexpected non-induction PHIs for fixup in non VPlan-native path");
  3378. fixNonInductionPHIs();
  3379. }
  3380. // At this point every instruction in the original loop is widened to a
  3381. // vector form. Now we need to fix the recurrences in the loop. These PHI
  3382. // nodes are currently empty because we did not want to introduce cycles.
  3383. // This is the second stage of vectorizing recurrences.
  3384. fixCrossIterationPHIs();
  3385. // Forget the original basic block.
  3386. PSE.getSE()->forgetLoop(OrigLoop);
  3387. // Fix-up external users of the induction variables.
  3388. for (auto &Entry : Legal->getInductionVars())
  3389. fixupIVUsers(Entry.first, Entry.second,
  3390. getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
  3391. IVEndValues[Entry.first], LoopMiddleBlock);
  3392. fixLCSSAPHIs();
  3393. for (Instruction *PI : PredicatedInstructions)
  3394. sinkScalarOperands(&*PI);
  3395. // Remove redundant induction instructions.
  3396. cse(LoopVectorBody);
  3397. // Set/update profile weights for the vector and remainder loops as original
  3398. // loop iterations are now distributed among them. Note that original loop
  3399. // represented by LoopScalarBody becomes remainder loop after vectorization.
  3400. //
  3401. // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
  3402. // end up getting slightly roughened result but that should be OK since
  3403. // profile is not inherently precise anyway. Note also possible bypass of
  3404. // vector code caused by legality checks is ignored, assigning all the weight
  3405. // to the vector loop, optimistically.
  3406. //
  3407. // For scalable vectorization we can't know at compile time how many iterations
  3408. // of the loop are handled in one vector iteration, so instead assume a pessimistic
  3409. // vscale of '1'.
  3410. setProfileInfoAfterUnrolling(
  3411. LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
  3412. LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
  3413. }
  3414. void InnerLoopVectorizer::fixCrossIterationPHIs() {
  3415. // In order to support recurrences we need to be able to vectorize Phi nodes.
  3416. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  3417. // stage #2: We now need to fix the recurrences by adding incoming edges to
  3418. // the currently empty PHI nodes. At this point every instruction in the
  3419. // original loop is widened to a vector form so we can use them to construct
  3420. // the incoming edges.
  3421. for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
  3422. // Handle first-order recurrences and reductions that need to be fixed.
  3423. if (Legal->isFirstOrderRecurrence(&Phi))
  3424. fixFirstOrderRecurrence(&Phi);
  3425. else if (Legal->isReductionVariable(&Phi))
  3426. fixReduction(&Phi);
  3427. }
  3428. }
  3429. void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
  3430. // This is the second phase of vectorizing first-order recurrences. An
  3431. // overview of the transformation is described below. Suppose we have the
  3432. // following loop.
  3433. //
  3434. // for (int i = 0; i < n; ++i)
  3435. // b[i] = a[i] - a[i - 1];
  3436. //
  3437. // There is a first-order recurrence on "a". For this loop, the shorthand
  3438. // scalar IR looks like:
  3439. //
  3440. // scalar.ph:
  3441. // s_init = a[-1]
  3442. // br scalar.body
  3443. //
  3444. // scalar.body:
  3445. // i = phi [0, scalar.ph], [i+1, scalar.body]
  3446. // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
  3447. // s2 = a[i]
  3448. // b[i] = s2 - s1
  3449. // br cond, scalar.body, ...
  3450. //
  3451. // In this example, s1 is a recurrence because it's value depends on the
  3452. // previous iteration. In the first phase of vectorization, we created a
  3453. // temporary value for s1. We now complete the vectorization and produce the
  3454. // shorthand vector IR shown below (for VF = 4, UF = 1).
  3455. //
  3456. // vector.ph:
  3457. // v_init = vector(..., ..., ..., a[-1])
  3458. // br vector.body
  3459. //
  3460. // vector.body
  3461. // i = phi [0, vector.ph], [i+4, vector.body]
  3462. // v1 = phi [v_init, vector.ph], [v2, vector.body]
  3463. // v2 = a[i, i+1, i+2, i+3];
  3464. // v3 = vector(v1(3), v2(0, 1, 2))
  3465. // b[i, i+1, i+2, i+3] = v2 - v3
  3466. // br cond, vector.body, middle.block
  3467. //
  3468. // middle.block:
  3469. // x = v2(3)
  3470. // br scalar.ph
  3471. //
  3472. // scalar.ph:
  3473. // s_init = phi [x, middle.block], [a[-1], otherwise]
  3474. // br scalar.body
  3475. //
  3476. // After execution completes the vector loop, we extract the next value of
  3477. // the recurrence (x) to use as the initial value in the scalar loop.
  3478. // Get the original loop preheader and single loop latch.
  3479. auto *Preheader = OrigLoop->getLoopPreheader();
  3480. auto *Latch = OrigLoop->getLoopLatch();
  3481. // Get the initial and previous values of the scalar recurrence.
  3482. auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
  3483. auto *Previous = Phi->getIncomingValueForBlock(Latch);
  3484. // Create a vector from the initial value.
  3485. auto *VectorInit = ScalarInit;
  3486. if (VF.isVector()) {
  3487. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  3488. assert(!VF.isScalable() && "VF is assumed to be non scalable.");
  3489. VectorInit = Builder.CreateInsertElement(
  3490. PoisonValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
  3491. Builder.getInt32(VF.getKnownMinValue() - 1), "vector.recur.init");
  3492. }
  3493. // We constructed a temporary phi node in the first phase of vectorization.
  3494. // This phi node will eventually be deleted.
  3495. Builder.SetInsertPoint(
  3496. cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
  3497. // Create a phi node for the new recurrence. The current value will either be
  3498. // the initial value inserted into a vector or loop-varying vector value.
  3499. auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
  3500. VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
  3501. // Get the vectorized previous value of the last part UF - 1. It appears last
  3502. // among all unrolled iterations, due to the order of their construction.
  3503. Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
  3504. // Find and set the insertion point after the previous value if it is an
  3505. // instruction.
  3506. BasicBlock::iterator InsertPt;
  3507. // Note that the previous value may have been constant-folded so it is not
  3508. // guaranteed to be an instruction in the vector loop.
  3509. // FIXME: Loop invariant values do not form recurrences. We should deal with
  3510. // them earlier.
  3511. if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart))
  3512. InsertPt = LoopVectorBody->getFirstInsertionPt();
  3513. else {
  3514. Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
  3515. if (isa<PHINode>(PreviousLastPart))
  3516. // If the previous value is a phi node, we should insert after all the phi
  3517. // nodes in the block containing the PHI to avoid breaking basic block
  3518. // verification. Note that the basic block may be different to
  3519. // LoopVectorBody, in case we predicate the loop.
  3520. InsertPt = PreviousInst->getParent()->getFirstInsertionPt();
  3521. else
  3522. InsertPt = ++PreviousInst->getIterator();
  3523. }
  3524. Builder.SetInsertPoint(&*InsertPt);
  3525. // We will construct a vector for the recurrence by combining the values for
  3526. // the current and previous iterations. This is the required shuffle mask.
  3527. assert(!VF.isScalable());
  3528. SmallVector<int, 8> ShuffleMask(VF.getKnownMinValue());
  3529. ShuffleMask[0] = VF.getKnownMinValue() - 1;
  3530. for (unsigned I = 1; I < VF.getKnownMinValue(); ++I)
  3531. ShuffleMask[I] = I + VF.getKnownMinValue() - 1;
  3532. // The vector from which to take the initial value for the current iteration
  3533. // (actual or unrolled). Initially, this is the vector phi node.
  3534. Value *Incoming = VecPhi;
  3535. // Shuffle the current and previous vector and update the vector parts.
  3536. for (unsigned Part = 0; Part < UF; ++Part) {
  3537. Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
  3538. Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
  3539. auto *Shuffle =
  3540. VF.isVector()
  3541. ? Builder.CreateShuffleVector(Incoming, PreviousPart, ShuffleMask)
  3542. : Incoming;
  3543. PhiPart->replaceAllUsesWith(Shuffle);
  3544. cast<Instruction>(PhiPart)->eraseFromParent();
  3545. VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
  3546. Incoming = PreviousPart;
  3547. }
  3548. // Fix the latch value of the new recurrence in the vector loop.
  3549. VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  3550. // Extract the last vector element in the middle block. This will be the
  3551. // initial value for the recurrence when jumping to the scalar loop.
  3552. auto *ExtractForScalar = Incoming;
  3553. if (VF.isVector()) {
  3554. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  3555. ExtractForScalar = Builder.CreateExtractElement(
  3556. ExtractForScalar, Builder.getInt32(VF.getKnownMinValue() - 1),
  3557. "vector.recur.extract");
  3558. }
  3559. // Extract the second last element in the middle block if the
  3560. // Phi is used outside the loop. We need to extract the phi itself
  3561. // and not the last element (the phi update in the current iteration). This
  3562. // will be the value when jumping to the exit block from the LoopMiddleBlock,
  3563. // when the scalar loop is not run at all.
  3564. Value *ExtractForPhiUsedOutsideLoop = nullptr;
  3565. if (VF.isVector())
  3566. ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
  3567. Incoming, Builder.getInt32(VF.getKnownMinValue() - 2),
  3568. "vector.recur.extract.for.phi");
  3569. // When loop is unrolled without vectorizing, initialize
  3570. // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
  3571. // `Incoming`. This is analogous to the vectorized case above: extracting the
  3572. // second last element when VF > 1.
  3573. else if (UF > 1)
  3574. ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
  3575. // Fix the initial value of the original recurrence in the scalar loop.
  3576. Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
  3577. auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
  3578. for (auto *BB : predecessors(LoopScalarPreHeader)) {
  3579. auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
  3580. Start->addIncoming(Incoming, BB);
  3581. }
  3582. Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
  3583. Phi->setName("scalar.recur");
  3584. // Finally, fix users of the recurrence outside the loop. The users will need
  3585. // either the last value of the scalar recurrence or the last value of the
  3586. // vector recurrence we extracted in the middle block. Since the loop is in
  3587. // LCSSA form, we just need to find all the phi nodes for the original scalar
  3588. // recurrence in the exit block, and then add an edge for the middle block.
  3589. // Note that LCSSA does not imply single entry when the original scalar loop
  3590. // had multiple exiting edges (as we always run the last iteration in the
  3591. // scalar epilogue); in that case, the exiting path through middle will be
  3592. // dynamically dead and the value picked for the phi doesn't matter.
  3593. for (PHINode &LCSSAPhi : LoopExitBlock->phis())
  3594. if (any_of(LCSSAPhi.incoming_values(),
  3595. [Phi](Value *V) { return V == Phi; }))
  3596. LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
  3597. }
  3598. void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
  3599. // Get it's reduction variable descriptor.
  3600. assert(Legal->isReductionVariable(Phi) &&
  3601. "Unable to find the reduction variable");
  3602. RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[Phi];
  3603. RecurKind RK = RdxDesc.getRecurrenceKind();
  3604. TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
  3605. Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
  3606. setDebugLocFromInst(Builder, ReductionStartValue);
  3607. bool IsInLoopReductionPhi = Cost->isInLoopReduction(Phi);
  3608. // This is the vector-clone of the value that leaves the loop.
  3609. Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
  3610. // Wrap flags are in general invalid after vectorization, clear them.
  3611. clearReductionWrapFlags(RdxDesc);
  3612. // Fix the vector-loop phi.
  3613. // Reductions do not have to start at zero. They can start with
  3614. // any loop invariant values.
  3615. BasicBlock *Latch = OrigLoop->getLoopLatch();
  3616. Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
  3617. for (unsigned Part = 0; Part < UF; ++Part) {
  3618. Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
  3619. Value *Val = getOrCreateVectorValue(LoopVal, Part);
  3620. cast<PHINode>(VecRdxPhi)
  3621. ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  3622. }
  3623. // Before each round, move the insertion point right between
  3624. // the PHIs and the values we are going to write.
  3625. // This allows us to write both PHINodes and the extractelement
  3626. // instructions.
  3627. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3628. setDebugLocFromInst(Builder, LoopExitInst);
  3629. // If tail is folded by masking, the vector value to leave the loop should be
  3630. // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
  3631. // instead of the former. For an inloop reduction the reduction will already
  3632. // be predicated, and does not need to be handled here.
  3633. if (Cost->foldTailByMasking() && !IsInLoopReductionPhi) {
  3634. for (unsigned Part = 0; Part < UF; ++Part) {
  3635. Value *VecLoopExitInst =
  3636. VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
  3637. Value *Sel = nullptr;
  3638. for (User *U : VecLoopExitInst->users()) {
  3639. if (isa<SelectInst>(U)) {
  3640. assert(!Sel && "Reduction exit feeding two selects");
  3641. Sel = U;
  3642. } else
  3643. assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
  3644. }
  3645. assert(Sel && "Reduction exit feeds no select");
  3646. VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, Sel);
  3647. // If the target can create a predicated operator for the reduction at no
  3648. // extra cost in the loop (for example a predicated vadd), it can be
  3649. // cheaper for the select to remain in the loop than be sunk out of it,
  3650. // and so use the select value for the phi instead of the old
  3651. // LoopExitValue.
  3652. RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[Phi];
  3653. if (PreferPredicatedReductionSelect ||
  3654. TTI->preferPredicatedReductionSelect(
  3655. RdxDesc.getOpcode(), Phi->getType(),
  3656. TargetTransformInfo::ReductionFlags())) {
  3657. auto *VecRdxPhi = cast<PHINode>(getOrCreateVectorValue(Phi, Part));
  3658. VecRdxPhi->setIncomingValueForBlock(
  3659. LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
  3660. }
  3661. }
  3662. }
  3663. // If the vector reduction can be performed in a smaller type, we truncate
  3664. // then extend the loop exit value to enable InstCombine to evaluate the
  3665. // entire expression in the smaller type.
  3666. if (VF.isVector() && Phi->getType() != RdxDesc.getRecurrenceType()) {
  3667. assert(!IsInLoopReductionPhi && "Unexpected truncated inloop reduction!");
  3668. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  3669. Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
  3670. Builder.SetInsertPoint(
  3671. LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
  3672. VectorParts RdxParts(UF);
  3673. for (unsigned Part = 0; Part < UF; ++Part) {
  3674. RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
  3675. Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3676. Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
  3677. : Builder.CreateZExt(Trunc, VecTy);
  3678. for (Value::user_iterator UI = RdxParts[Part]->user_begin();
  3679. UI != RdxParts[Part]->user_end();)
  3680. if (*UI != Trunc) {
  3681. (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
  3682. RdxParts[Part] = Extnd;
  3683. } else {
  3684. ++UI;
  3685. }
  3686. }
  3687. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3688. for (unsigned Part = 0; Part < UF; ++Part) {
  3689. RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3690. VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
  3691. }
  3692. }
  3693. // Reduce all of the unrolled parts into a single vector.
  3694. Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
  3695. unsigned Op = RecurrenceDescriptor::getOpcode(RK);
  3696. // The middle block terminator has already been assigned a DebugLoc here (the
  3697. // OrigLoop's single latch terminator). We want the whole middle block to
  3698. // appear to execute on this line because: (a) it is all compiler generated,
  3699. // (b) these instructions are always executed after evaluating the latch
  3700. // conditional branch, and (c) other passes may add new predecessors which
  3701. // terminate on this line. This is the easiest way to ensure we don't
  3702. // accidentally cause an extra step back into the loop while debugging.
  3703. setDebugLocFromInst(Builder, LoopMiddleBlock->getTerminator());
  3704. for (unsigned Part = 1; Part < UF; ++Part) {
  3705. Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
  3706. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  3707. // Floating point operations had to be 'fast' to enable the reduction.
  3708. ReducedPartRdx = addFastMathFlag(
  3709. Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
  3710. ReducedPartRdx, "bin.rdx"),
  3711. RdxDesc.getFastMathFlags());
  3712. else
  3713. ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
  3714. }
  3715. // Create the reduction after the loop. Note that inloop reductions create the
  3716. // target reduction in the loop using a Reduction recipe.
  3717. if (VF.isVector() && !IsInLoopReductionPhi) {
  3718. ReducedPartRdx =
  3719. createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx);
  3720. // If the reduction can be performed in a smaller type, we need to extend
  3721. // the reduction to the wider type before we branch to the original loop.
  3722. if (Phi->getType() != RdxDesc.getRecurrenceType())
  3723. ReducedPartRdx =
  3724. RdxDesc.isSigned()
  3725. ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
  3726. : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
  3727. }
  3728. // Create a phi node that merges control-flow from the backedge-taken check
  3729. // block and the middle block.
  3730. PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
  3731. LoopScalarPreHeader->getTerminator());
  3732. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
  3733. BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
  3734. BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3735. // Now, we need to fix the users of the reduction variable
  3736. // inside and outside of the scalar remainder loop.
  3737. // We know that the loop is in LCSSA form. We need to update the PHI nodes
  3738. // in the exit blocks. See comment on analogous loop in
  3739. // fixFirstOrderRecurrence for a more complete explaination of the logic.
  3740. for (PHINode &LCSSAPhi : LoopExitBlock->phis())
  3741. if (any_of(LCSSAPhi.incoming_values(),
  3742. [LoopExitInst](Value *V) { return V == LoopExitInst; }))
  3743. LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3744. // Fix the scalar loop reduction variable with the incoming reduction sum
  3745. // from the vector body and from the backedge value.
  3746. int IncomingEdgeBlockIdx =
  3747. Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
  3748. assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
  3749. // Pick the other block.
  3750. int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
  3751. Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
  3752. Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
  3753. }
  3754. void InnerLoopVectorizer::clearReductionWrapFlags(
  3755. RecurrenceDescriptor &RdxDesc) {
  3756. RecurKind RK = RdxDesc.getRecurrenceKind();
  3757. if (RK != RecurKind::Add && RK != RecurKind::Mul)
  3758. return;
  3759. Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
  3760. assert(LoopExitInstr && "null loop exit instruction");
  3761. SmallVector<Instruction *, 8> Worklist;
  3762. SmallPtrSet<Instruction *, 8> Visited;
  3763. Worklist.push_back(LoopExitInstr);
  3764. Visited.insert(LoopExitInstr);
  3765. while (!Worklist.empty()) {
  3766. Instruction *Cur = Worklist.pop_back_val();
  3767. if (isa<OverflowingBinaryOperator>(Cur))
  3768. for (unsigned Part = 0; Part < UF; ++Part) {
  3769. Value *V = getOrCreateVectorValue(Cur, Part);
  3770. cast<Instruction>(V)->dropPoisonGeneratingFlags();
  3771. }
  3772. for (User *U : Cur->users()) {
  3773. Instruction *UI = cast<Instruction>(U);
  3774. if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
  3775. Visited.insert(UI).second)
  3776. Worklist.push_back(UI);
  3777. }
  3778. }
  3779. }
  3780. void InnerLoopVectorizer::fixLCSSAPHIs() {
  3781. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3782. if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
  3783. // Some phis were already hand updated by the reduction and recurrence
  3784. // code above, leave them alone.
  3785. continue;
  3786. auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
  3787. // Non-instruction incoming values will have only one value.
  3788. unsigned LastLane = 0;
  3789. if (isa<Instruction>(IncomingValue))
  3790. LastLane = Cost->isUniformAfterVectorization(
  3791. cast<Instruction>(IncomingValue), VF)
  3792. ? 0
  3793. : VF.getKnownMinValue() - 1;
  3794. assert((!VF.isScalable() || LastLane == 0) &&
  3795. "scalable vectors dont support non-uniform scalars yet");
  3796. // Can be a loop invariant incoming value or the last scalar value to be
  3797. // extracted from the vectorized loop.
  3798. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  3799. Value *lastIncomingValue =
  3800. getOrCreateScalarValue(IncomingValue, { UF - 1, LastLane });
  3801. LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
  3802. }
  3803. }
  3804. void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
  3805. // The basic block and loop containing the predicated instruction.
  3806. auto *PredBB = PredInst->getParent();
  3807. auto *VectorLoop = LI->getLoopFor(PredBB);
  3808. // Initialize a worklist with the operands of the predicated instruction.
  3809. SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
  3810. // Holds instructions that we need to analyze again. An instruction may be
  3811. // reanalyzed if we don't yet know if we can sink it or not.
  3812. SmallVector<Instruction *, 8> InstsToReanalyze;
  3813. // Returns true if a given use occurs in the predicated block. Phi nodes use
  3814. // their operands in their corresponding predecessor blocks.
  3815. auto isBlockOfUsePredicated = [&](Use &U) -> bool {
  3816. auto *I = cast<Instruction>(U.getUser());
  3817. BasicBlock *BB = I->getParent();
  3818. if (auto *Phi = dyn_cast<PHINode>(I))
  3819. BB = Phi->getIncomingBlock(
  3820. PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
  3821. return BB == PredBB;
  3822. };
  3823. // Iteratively sink the scalarized operands of the predicated instruction
  3824. // into the block we created for it. When an instruction is sunk, it's
  3825. // operands are then added to the worklist. The algorithm ends after one pass
  3826. // through the worklist doesn't sink a single instruction.
  3827. bool Changed;
  3828. do {
  3829. // Add the instructions that need to be reanalyzed to the worklist, and
  3830. // reset the changed indicator.
  3831. Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
  3832. InstsToReanalyze.clear();
  3833. Changed = false;
  3834. while (!Worklist.empty()) {
  3835. auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
  3836. // We can't sink an instruction if it is a phi node, is already in the
  3837. // predicated block, is not in the loop, or may have side effects.
  3838. if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
  3839. !VectorLoop->contains(I) || I->mayHaveSideEffects())
  3840. continue;
  3841. // It's legal to sink the instruction if all its uses occur in the
  3842. // predicated block. Otherwise, there's nothing to do yet, and we may
  3843. // need to reanalyze the instruction.
  3844. if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
  3845. InstsToReanalyze.push_back(I);
  3846. continue;
  3847. }
  3848. // Move the instruction to the beginning of the predicated block, and add
  3849. // it's operands to the worklist.
  3850. I->moveBefore(&*PredBB->getFirstInsertionPt());
  3851. Worklist.insert(I->op_begin(), I->op_end());
  3852. // The sinking may have enabled other instructions to be sunk, so we will
  3853. // need to iterate.
  3854. Changed = true;
  3855. }
  3856. } while (Changed);
  3857. }
  3858. void InnerLoopVectorizer::fixNonInductionPHIs() {
  3859. for (PHINode *OrigPhi : OrigPHIsToFix) {
  3860. PHINode *NewPhi =
  3861. cast<PHINode>(VectorLoopValueMap.getVectorValue(OrigPhi, 0));
  3862. unsigned NumIncomingValues = OrigPhi->getNumIncomingValues();
  3863. SmallVector<BasicBlock *, 2> ScalarBBPredecessors(
  3864. predecessors(OrigPhi->getParent()));
  3865. SmallVector<BasicBlock *, 2> VectorBBPredecessors(
  3866. predecessors(NewPhi->getParent()));
  3867. assert(ScalarBBPredecessors.size() == VectorBBPredecessors.size() &&
  3868. "Scalar and Vector BB should have the same number of predecessors");
  3869. // The insertion point in Builder may be invalidated by the time we get
  3870. // here. Force the Builder insertion point to something valid so that we do
  3871. // not run into issues during insertion point restore in
  3872. // getOrCreateVectorValue calls below.
  3873. Builder.SetInsertPoint(NewPhi);
  3874. // The predecessor order is preserved and we can rely on mapping between
  3875. // scalar and vector block predecessors.
  3876. for (unsigned i = 0; i < NumIncomingValues; ++i) {
  3877. BasicBlock *NewPredBB = VectorBBPredecessors[i];
  3878. // When looking up the new scalar/vector values to fix up, use incoming
  3879. // values from original phi.
  3880. Value *ScIncV =
  3881. OrigPhi->getIncomingValueForBlock(ScalarBBPredecessors[i]);
  3882. // Scalar incoming value may need a broadcast
  3883. Value *NewIncV = getOrCreateVectorValue(ScIncV, 0);
  3884. NewPhi->addIncoming(NewIncV, NewPredBB);
  3885. }
  3886. }
  3887. }
  3888. void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPValue *VPDef,
  3889. VPUser &Operands, unsigned UF,
  3890. ElementCount VF, bool IsPtrLoopInvariant,
  3891. SmallBitVector &IsIndexLoopInvariant,
  3892. VPTransformState &State) {
  3893. // Construct a vector GEP by widening the operands of the scalar GEP as
  3894. // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
  3895. // results in a vector of pointers when at least one operand of the GEP
  3896. // is vector-typed. Thus, to keep the representation compact, we only use
  3897. // vector-typed operands for loop-varying values.
  3898. if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
  3899. // If we are vectorizing, but the GEP has only loop-invariant operands,
  3900. // the GEP we build (by only using vector-typed operands for
  3901. // loop-varying values) would be a scalar pointer. Thus, to ensure we
  3902. // produce a vector of pointers, we need to either arbitrarily pick an
  3903. // operand to broadcast, or broadcast a clone of the original GEP.
  3904. // Here, we broadcast a clone of the original.
  3905. //
  3906. // TODO: If at some point we decide to scalarize instructions having
  3907. // loop-invariant operands, this special case will no longer be
  3908. // required. We would add the scalarization decision to
  3909. // collectLoopScalars() and teach getVectorValue() to broadcast
  3910. // the lane-zero scalar value.
  3911. auto *Clone = Builder.Insert(GEP->clone());
  3912. for (unsigned Part = 0; Part < UF; ++Part) {
  3913. Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
  3914. State.set(VPDef, GEP, EntryPart, Part);
  3915. addMetadata(EntryPart, GEP);
  3916. }
  3917. } else {
  3918. // If the GEP has at least one loop-varying operand, we are sure to
  3919. // produce a vector of pointers. But if we are only unrolling, we want
  3920. // to produce a scalar GEP for each unroll part. Thus, the GEP we
  3921. // produce with the code below will be scalar (if VF == 1) or vector
  3922. // (otherwise). Note that for the unroll-only case, we still maintain
  3923. // values in the vector mapping with initVector, as we do for other
  3924. // instructions.
  3925. for (unsigned Part = 0; Part < UF; ++Part) {
  3926. // The pointer operand of the new GEP. If it's loop-invariant, we
  3927. // won't broadcast it.
  3928. auto *Ptr = IsPtrLoopInvariant ? State.get(Operands.getOperand(0), {0, 0})
  3929. : State.get(Operands.getOperand(0), Part);
  3930. // Collect all the indices for the new GEP. If any index is
  3931. // loop-invariant, we won't broadcast it.
  3932. SmallVector<Value *, 4> Indices;
  3933. for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
  3934. VPValue *Operand = Operands.getOperand(I);
  3935. if (IsIndexLoopInvariant[I - 1])
  3936. Indices.push_back(State.get(Operand, {0, 0}));
  3937. else
  3938. Indices.push_back(State.get(Operand, Part));
  3939. }
  3940. // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
  3941. // but it should be a vector, otherwise.
  3942. auto *NewGEP =
  3943. GEP->isInBounds()
  3944. ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
  3945. Indices)
  3946. : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
  3947. assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
  3948. "NewGEP is not a pointer vector");
  3949. State.set(VPDef, GEP, NewGEP, Part);
  3950. addMetadata(NewGEP, GEP);
  3951. }
  3952. }
  3953. }
  3954. void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
  3955. RecurrenceDescriptor *RdxDesc,
  3956. Value *StartV, unsigned UF,
  3957. ElementCount VF) {
  3958. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  3959. PHINode *P = cast<PHINode>(PN);
  3960. if (EnableVPlanNativePath) {
  3961. // Currently we enter here in the VPlan-native path for non-induction
  3962. // PHIs where all control flow is uniform. We simply widen these PHIs.
  3963. // Create a vector phi with no operands - the vector phi operands will be
  3964. // set at the end of vector code generation.
  3965. Type *VecTy =
  3966. (VF.isScalar()) ? PN->getType() : VectorType::get(PN->getType(), VF);
  3967. Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
  3968. VectorLoopValueMap.setVectorValue(P, 0, VecPhi);
  3969. OrigPHIsToFix.push_back(P);
  3970. return;
  3971. }
  3972. assert(PN->getParent() == OrigLoop->getHeader() &&
  3973. "Non-header phis should have been handled elsewhere");
  3974. // In order to support recurrences we need to be able to vectorize Phi nodes.
  3975. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  3976. // stage #1: We create a new vector PHI node with no incoming edges. We'll use
  3977. // this value when we vectorize all of the instructions that use the PHI.
  3978. if (RdxDesc || Legal->isFirstOrderRecurrence(P)) {
  3979. Value *Iden = nullptr;
  3980. bool ScalarPHI =
  3981. (VF.isScalar()) || Cost->isInLoopReduction(cast<PHINode>(PN));
  3982. Type *VecTy =
  3983. ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), VF);
  3984. if (RdxDesc) {
  3985. assert(Legal->isReductionVariable(P) && StartV &&
  3986. "RdxDesc should only be set for reduction variables; in that case "
  3987. "a StartV is also required");
  3988. RecurKind RK = RdxDesc->getRecurrenceKind();
  3989. if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK)) {
  3990. // MinMax reduction have the start value as their identify.
  3991. if (ScalarPHI) {
  3992. Iden = StartV;
  3993. } else {
  3994. IRBuilderBase::InsertPointGuard IPBuilder(Builder);
  3995. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  3996. StartV = Iden = Builder.CreateVectorSplat(VF, StartV, "minmax.ident");
  3997. }
  3998. } else {
  3999. Constant *IdenC = RecurrenceDescriptor::getRecurrenceIdentity(
  4000. RK, VecTy->getScalarType());
  4001. Iden = IdenC;
  4002. if (!ScalarPHI) {
  4003. Iden = ConstantVector::getSplat(VF, IdenC);
  4004. IRBuilderBase::InsertPointGuard IPBuilder(Builder);
  4005. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  4006. Constant *Zero = Builder.getInt32(0);
  4007. StartV = Builder.CreateInsertElement(Iden, StartV, Zero);
  4008. }
  4009. }
  4010. }
  4011. for (unsigned Part = 0; Part < UF; ++Part) {
  4012. // This is phase one of vectorizing PHIs.
  4013. Value *EntryPart = PHINode::Create(
  4014. VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
  4015. VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
  4016. if (StartV) {
  4017. // Make sure to add the reduction start value only to the
  4018. // first unroll part.
  4019. Value *StartVal = (Part == 0) ? StartV : Iden;
  4020. cast<PHINode>(EntryPart)->addIncoming(StartVal, LoopVectorPreHeader);
  4021. }
  4022. }
  4023. return;
  4024. }
  4025. assert(!Legal->isReductionVariable(P) &&
  4026. "reductions should be handled above");
  4027. setDebugLocFromInst(Builder, P);
  4028. // This PHINode must be an induction variable.
  4029. // Make sure that we know about it.
  4030. assert(Legal->getInductionVars().count(P) && "Not an induction variable");
  4031. InductionDescriptor II = Legal->getInductionVars().lookup(P);
  4032. const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  4033. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  4034. // which can be found from the original scalar operations.
  4035. switch (II.getKind()) {
  4036. case InductionDescriptor::IK_NoInduction:
  4037. llvm_unreachable("Unknown induction");
  4038. case InductionDescriptor::IK_IntInduction:
  4039. case InductionDescriptor::IK_FpInduction:
  4040. llvm_unreachable("Integer/fp induction is handled elsewhere.");
  4041. case InductionDescriptor::IK_PtrInduction: {
  4042. // Handle the pointer induction variable case.
  4043. assert(P->getType()->isPointerTy() && "Unexpected type.");
  4044. if (Cost->isScalarAfterVectorization(P, VF)) {
  4045. // This is the normalized GEP that starts counting at zero.
  4046. Value *PtrInd =
  4047. Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
  4048. // Determine the number of scalars we need to generate for each unroll
  4049. // iteration. If the instruction is uniform, we only need to generate the
  4050. // first lane. Otherwise, we generate all VF values.
  4051. unsigned Lanes =
  4052. Cost->isUniformAfterVectorization(P, VF) ? 1 : VF.getKnownMinValue();
  4053. for (unsigned Part = 0; Part < UF; ++Part) {
  4054. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  4055. Constant *Idx = ConstantInt::get(PtrInd->getType(),
  4056. Lane + Part * VF.getKnownMinValue());
  4057. Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
  4058. Value *SclrGep =
  4059. emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
  4060. SclrGep->setName("next.gep");
  4061. VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
  4062. }
  4063. }
  4064. return;
  4065. }
  4066. assert(isa<SCEVConstant>(II.getStep()) &&
  4067. "Induction step not a SCEV constant!");
  4068. Type *PhiType = II.getStep()->getType();
  4069. // Build a pointer phi
  4070. Value *ScalarStartValue = II.getStartValue();
  4071. Type *ScStValueType = ScalarStartValue->getType();
  4072. PHINode *NewPointerPhi =
  4073. PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
  4074. NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
  4075. // A pointer induction, performed by using a gep
  4076. BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
  4077. Instruction *InductionLoc = LoopLatch->getTerminator();
  4078. const SCEV *ScalarStep = II.getStep();
  4079. SCEVExpander Exp(*PSE.getSE(), DL, "induction");
  4080. Value *ScalarStepValue =
  4081. Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
  4082. Value *InductionGEP = GetElementPtrInst::Create(
  4083. ScStValueType->getPointerElementType(), NewPointerPhi,
  4084. Builder.CreateMul(
  4085. ScalarStepValue,
  4086. ConstantInt::get(PhiType, VF.getKnownMinValue() * UF)),
  4087. "ptr.ind", InductionLoc);
  4088. NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
  4089. // Create UF many actual address geps that use the pointer
  4090. // phi as base and a vectorized version of the step value
  4091. // (<step*0, ..., step*N>) as offset.
  4092. for (unsigned Part = 0; Part < UF; ++Part) {
  4093. SmallVector<Constant *, 8> Indices;
  4094. // Create a vector of consecutive numbers from zero to VF.
  4095. for (unsigned i = 0; i < VF.getKnownMinValue(); ++i)
  4096. Indices.push_back(
  4097. ConstantInt::get(PhiType, i + Part * VF.getKnownMinValue()));
  4098. Constant *StartOffset = ConstantVector::get(Indices);
  4099. Value *GEP = Builder.CreateGEP(
  4100. ScStValueType->getPointerElementType(), NewPointerPhi,
  4101. Builder.CreateMul(
  4102. StartOffset,
  4103. Builder.CreateVectorSplat(VF.getKnownMinValue(), ScalarStepValue),
  4104. "vector.gep"));
  4105. VectorLoopValueMap.setVectorValue(P, Part, GEP);
  4106. }
  4107. }
  4108. }
  4109. }
  4110. /// A helper function for checking whether an integer division-related
  4111. /// instruction may divide by zero (in which case it must be predicated if
  4112. /// executed conditionally in the scalar code).
  4113. /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
  4114. /// Non-zero divisors that are non compile-time constants will not be
  4115. /// converted into multiplication, so we will still end up scalarizing
  4116. /// the division, but can do so w/o predication.
  4117. static bool mayDivideByZero(Instruction &I) {
  4118. assert((I.getOpcode() == Instruction::UDiv ||
  4119. I.getOpcode() == Instruction::SDiv ||
  4120. I.getOpcode() == Instruction::URem ||
  4121. I.getOpcode() == Instruction::SRem) &&
  4122. "Unexpected instruction");
  4123. Value *Divisor = I.getOperand(1);
  4124. auto *CInt = dyn_cast<ConstantInt>(Divisor);
  4125. return !CInt || CInt->isZero();
  4126. }
  4127. void InnerLoopVectorizer::widenInstruction(Instruction &I, VPValue *Def,
  4128. VPUser &User,
  4129. VPTransformState &State) {
  4130. switch (I.getOpcode()) {
  4131. case Instruction::Call:
  4132. case Instruction::Br:
  4133. case Instruction::PHI:
  4134. case Instruction::GetElementPtr:
  4135. case Instruction::Select:
  4136. llvm_unreachable("This instruction is handled by a different recipe.");
  4137. case Instruction::UDiv:
  4138. case Instruction::SDiv:
  4139. case Instruction::SRem:
  4140. case Instruction::URem:
  4141. case Instruction::Add:
  4142. case Instruction::FAdd:
  4143. case Instruction::Sub:
  4144. case Instruction::FSub:
  4145. case Instruction::FNeg:
  4146. case Instruction::Mul:
  4147. case Instruction::FMul:
  4148. case Instruction::FDiv:
  4149. case Instruction::FRem:
  4150. case Instruction::Shl:
  4151. case Instruction::LShr:
  4152. case Instruction::AShr:
  4153. case Instruction::And:
  4154. case Instruction::Or:
  4155. case Instruction::Xor: {
  4156. // Just widen unops and binops.
  4157. setDebugLocFromInst(Builder, &I);
  4158. for (unsigned Part = 0; Part < UF; ++Part) {
  4159. SmallVector<Value *, 2> Ops;
  4160. for (VPValue *VPOp : User.operands())
  4161. Ops.push_back(State.get(VPOp, Part));
  4162. Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
  4163. if (auto *VecOp = dyn_cast<Instruction>(V))
  4164. VecOp->copyIRFlags(&I);
  4165. // Use this vector value for all users of the original instruction.
  4166. State.set(Def, &I, V, Part);
  4167. addMetadata(V, &I);
  4168. }
  4169. break;
  4170. }
  4171. case Instruction::ICmp:
  4172. case Instruction::FCmp: {
  4173. // Widen compares. Generate vector compares.
  4174. bool FCmp = (I.getOpcode() == Instruction::FCmp);
  4175. auto *Cmp = cast<CmpInst>(&I);
  4176. setDebugLocFromInst(Builder, Cmp);
  4177. for (unsigned Part = 0; Part < UF; ++Part) {
  4178. Value *A = State.get(User.getOperand(0), Part);
  4179. Value *B = State.get(User.getOperand(1), Part);
  4180. Value *C = nullptr;
  4181. if (FCmp) {
  4182. // Propagate fast math flags.
  4183. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  4184. Builder.setFastMathFlags(Cmp->getFastMathFlags());
  4185. C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
  4186. } else {
  4187. C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
  4188. }
  4189. State.set(Def, &I, C, Part);
  4190. addMetadata(C, &I);
  4191. }
  4192. break;
  4193. }
  4194. case Instruction::ZExt:
  4195. case Instruction::SExt:
  4196. case Instruction::FPToUI:
  4197. case Instruction::FPToSI:
  4198. case Instruction::FPExt:
  4199. case Instruction::PtrToInt:
  4200. case Instruction::IntToPtr:
  4201. case Instruction::SIToFP:
  4202. case Instruction::UIToFP:
  4203. case Instruction::Trunc:
  4204. case Instruction::FPTrunc:
  4205. case Instruction::BitCast: {
  4206. auto *CI = cast<CastInst>(&I);
  4207. setDebugLocFromInst(Builder, CI);
  4208. /// Vectorize casts.
  4209. Type *DestTy =
  4210. (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
  4211. for (unsigned Part = 0; Part < UF; ++Part) {
  4212. Value *A = State.get(User.getOperand(0), Part);
  4213. Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
  4214. State.set(Def, &I, Cast, Part);
  4215. addMetadata(Cast, &I);
  4216. }
  4217. break;
  4218. }
  4219. default:
  4220. // This instruction is not vectorized by simple widening.
  4221. LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
  4222. llvm_unreachable("Unhandled instruction!");
  4223. } // end of switch.
  4224. }
  4225. void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
  4226. VPUser &ArgOperands,
  4227. VPTransformState &State) {
  4228. assert(!isa<DbgInfoIntrinsic>(I) &&
  4229. "DbgInfoIntrinsic should have been dropped during VPlan construction");
  4230. setDebugLocFromInst(Builder, &I);
  4231. Module *M = I.getParent()->getParent()->getParent();
  4232. auto *CI = cast<CallInst>(&I);
  4233. SmallVector<Type *, 4> Tys;
  4234. for (Value *ArgOperand : CI->arg_operands())
  4235. Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
  4236. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  4237. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  4238. // version of the instruction.
  4239. // Is it beneficial to perform intrinsic call compared to lib call?
  4240. bool NeedToScalarize = false;
  4241. InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
  4242. InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
  4243. bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
  4244. assert((UseVectorIntrinsic || !NeedToScalarize) &&
  4245. "Instruction should be scalarized elsewhere.");
  4246. assert(IntrinsicCost.isValid() && CallCost.isValid() &&
  4247. "Cannot have invalid costs while widening");
  4248. for (unsigned Part = 0; Part < UF; ++Part) {
  4249. SmallVector<Value *, 4> Args;
  4250. for (auto &I : enumerate(ArgOperands.operands())) {
  4251. // Some intrinsics have a scalar argument - don't replace it with a
  4252. // vector.
  4253. Value *Arg;
  4254. if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
  4255. Arg = State.get(I.value(), Part);
  4256. else
  4257. Arg = State.get(I.value(), {0, 0});
  4258. Args.push_back(Arg);
  4259. }
  4260. Function *VectorF;
  4261. if (UseVectorIntrinsic) {
  4262. // Use vector version of the intrinsic.
  4263. Type *TysForDecl[] = {CI->getType()};
  4264. if (VF.isVector()) {
  4265. assert(!VF.isScalable() && "VF is assumed to be non scalable.");
  4266. TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
  4267. }
  4268. VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
  4269. assert(VectorF && "Can't retrieve vector intrinsic.");
  4270. } else {
  4271. // Use vector version of the function call.
  4272. const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
  4273. #ifndef NDEBUG
  4274. assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
  4275. "Can't create vector function.");
  4276. #endif
  4277. VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
  4278. }
  4279. SmallVector<OperandBundleDef, 1> OpBundles;
  4280. CI->getOperandBundlesAsDefs(OpBundles);
  4281. CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
  4282. if (isa<FPMathOperator>(V))
  4283. V->copyFastMathFlags(CI);
  4284. State.set(Def, &I, V, Part);
  4285. addMetadata(V, &I);
  4286. }
  4287. }
  4288. void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I, VPValue *VPDef,
  4289. VPUser &Operands,
  4290. bool InvariantCond,
  4291. VPTransformState &State) {
  4292. setDebugLocFromInst(Builder, &I);
  4293. // The condition can be loop invariant but still defined inside the
  4294. // loop. This means that we can't just use the original 'cond' value.
  4295. // We have to take the 'vectorized' value and pick the first lane.
  4296. // Instcombine will make this a no-op.
  4297. auto *InvarCond =
  4298. InvariantCond ? State.get(Operands.getOperand(0), {0, 0}) : nullptr;
  4299. for (unsigned Part = 0; Part < UF; ++Part) {
  4300. Value *Cond =
  4301. InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
  4302. Value *Op0 = State.get(Operands.getOperand(1), Part);
  4303. Value *Op1 = State.get(Operands.getOperand(2), Part);
  4304. Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
  4305. State.set(VPDef, &I, Sel, Part);
  4306. addMetadata(Sel, &I);
  4307. }
  4308. }
  4309. void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
  4310. // We should not collect Scalars more than once per VF. Right now, this
  4311. // function is called from collectUniformsAndScalars(), which already does
  4312. // this check. Collecting Scalars for VF=1 does not make any sense.
  4313. assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
  4314. "This function should not be visited twice for the same VF");
  4315. SmallSetVector<Instruction *, 8> Worklist;
  4316. // These sets are used to seed the analysis with pointers used by memory
  4317. // accesses that will remain scalar.
  4318. SmallSetVector<Instruction *, 8> ScalarPtrs;
  4319. SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
  4320. auto *Latch = TheLoop->getLoopLatch();
  4321. // A helper that returns true if the use of Ptr by MemAccess will be scalar.
  4322. // The pointer operands of loads and stores will be scalar as long as the
  4323. // memory access is not a gather or scatter operation. The value operand of a
  4324. // store will remain scalar if the store is scalarized.
  4325. auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
  4326. InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
  4327. assert(WideningDecision != CM_Unknown &&
  4328. "Widening decision should be ready at this moment");
  4329. if (auto *Store = dyn_cast<StoreInst>(MemAccess))
  4330. if (Ptr == Store->getValueOperand())
  4331. return WideningDecision == CM_Scalarize;
  4332. assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
  4333. "Ptr is neither a value or pointer operand");
  4334. return WideningDecision != CM_GatherScatter;
  4335. };
  4336. // A helper that returns true if the given value is a bitcast or
  4337. // getelementptr instruction contained in the loop.
  4338. auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
  4339. return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
  4340. isa<GetElementPtrInst>(V)) &&
  4341. !TheLoop->isLoopInvariant(V);
  4342. };
  4343. auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
  4344. if (!isa<PHINode>(Ptr) ||
  4345. !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
  4346. return false;
  4347. auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
  4348. if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
  4349. return false;
  4350. return isScalarUse(MemAccess, Ptr);
  4351. };
  4352. // A helper that evaluates a memory access's use of a pointer. If the
  4353. // pointer is actually the pointer induction of a loop, it is being
  4354. // inserted into Worklist. If the use will be a scalar use, and the
  4355. // pointer is only used by memory accesses, we place the pointer in
  4356. // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
  4357. auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
  4358. if (isScalarPtrInduction(MemAccess, Ptr)) {
  4359. Worklist.insert(cast<Instruction>(Ptr));
  4360. Instruction *Update = cast<Instruction>(
  4361. cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
  4362. Worklist.insert(Update);
  4363. LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
  4364. << "\n");
  4365. LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Update
  4366. << "\n");
  4367. return;
  4368. }
  4369. // We only care about bitcast and getelementptr instructions contained in
  4370. // the loop.
  4371. if (!isLoopVaryingBitCastOrGEP(Ptr))
  4372. return;
  4373. // If the pointer has already been identified as scalar (e.g., if it was
  4374. // also identified as uniform), there's nothing to do.
  4375. auto *I = cast<Instruction>(Ptr);
  4376. if (Worklist.count(I))
  4377. return;
  4378. // If the use of the pointer will be a scalar use, and all users of the
  4379. // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
  4380. // place the pointer in PossibleNonScalarPtrs.
  4381. if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
  4382. return isa<LoadInst>(U) || isa<StoreInst>(U);
  4383. }))
  4384. ScalarPtrs.insert(I);
  4385. else
  4386. PossibleNonScalarPtrs.insert(I);
  4387. };
  4388. // We seed the scalars analysis with three classes of instructions: (1)
  4389. // instructions marked uniform-after-vectorization and (2) bitcast,
  4390. // getelementptr and (pointer) phi instructions used by memory accesses
  4391. // requiring a scalar use.
  4392. //
  4393. // (1) Add to the worklist all instructions that have been identified as
  4394. // uniform-after-vectorization.
  4395. Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
  4396. // (2) Add to the worklist all bitcast and getelementptr instructions used by
  4397. // memory accesses requiring a scalar use. The pointer operands of loads and
  4398. // stores will be scalar as long as the memory accesses is not a gather or
  4399. // scatter operation. The value operand of a store will remain scalar if the
  4400. // store is scalarized.
  4401. for (auto *BB : TheLoop->blocks())
  4402. for (auto &I : *BB) {
  4403. if (auto *Load = dyn_cast<LoadInst>(&I)) {
  4404. evaluatePtrUse(Load, Load->getPointerOperand());
  4405. } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
  4406. evaluatePtrUse(Store, Store->getPointerOperand());
  4407. evaluatePtrUse(Store, Store->getValueOperand());
  4408. }
  4409. }
  4410. for (auto *I : ScalarPtrs)
  4411. if (!PossibleNonScalarPtrs.count(I)) {
  4412. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
  4413. Worklist.insert(I);
  4414. }
  4415. // Insert the forced scalars.
  4416. // FIXME: Currently widenPHIInstruction() often creates a dead vector
  4417. // induction variable when the PHI user is scalarized.
  4418. auto ForcedScalar = ForcedScalars.find(VF);
  4419. if (ForcedScalar != ForcedScalars.end())
  4420. for (auto *I : ForcedScalar->second)
  4421. Worklist.insert(I);
  4422. // Expand the worklist by looking through any bitcasts and getelementptr
  4423. // instructions we've already identified as scalar. This is similar to the
  4424. // expansion step in collectLoopUniforms(); however, here we're only
  4425. // expanding to include additional bitcasts and getelementptr instructions.
  4426. unsigned Idx = 0;
  4427. while (Idx != Worklist.size()) {
  4428. Instruction *Dst = Worklist[Idx++];
  4429. if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
  4430. continue;
  4431. auto *Src = cast<Instruction>(Dst->getOperand(0));
  4432. if (llvm::all_of(Src->users(), [&](User *U) -> bool {
  4433. auto *J = cast<Instruction>(U);
  4434. return !TheLoop->contains(J) || Worklist.count(J) ||
  4435. ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
  4436. isScalarUse(J, Src));
  4437. })) {
  4438. Worklist.insert(Src);
  4439. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
  4440. }
  4441. }
  4442. // An induction variable will remain scalar if all users of the induction
  4443. // variable and induction variable update remain scalar.
  4444. for (auto &Induction : Legal->getInductionVars()) {
  4445. auto *Ind = Induction.first;
  4446. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  4447. // If tail-folding is applied, the primary induction variable will be used
  4448. // to feed a vector compare.
  4449. if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
  4450. continue;
  4451. // Determine if all users of the induction variable are scalar after
  4452. // vectorization.
  4453. auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  4454. auto *I = cast<Instruction>(U);
  4455. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
  4456. });
  4457. if (!ScalarInd)
  4458. continue;
  4459. // Determine if all users of the induction variable update instruction are
  4460. // scalar after vectorization.
  4461. auto ScalarIndUpdate =
  4462. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  4463. auto *I = cast<Instruction>(U);
  4464. return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
  4465. });
  4466. if (!ScalarIndUpdate)
  4467. continue;
  4468. // The induction variable and its update instruction will remain scalar.
  4469. Worklist.insert(Ind);
  4470. Worklist.insert(IndUpdate);
  4471. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
  4472. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
  4473. << "\n");
  4474. }
  4475. Scalars[VF].insert(Worklist.begin(), Worklist.end());
  4476. }
  4477. bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I,
  4478. ElementCount VF) {
  4479. if (!blockNeedsPredication(I->getParent()))
  4480. return false;
  4481. switch(I->getOpcode()) {
  4482. default:
  4483. break;
  4484. case Instruction::Load:
  4485. case Instruction::Store: {
  4486. if (!Legal->isMaskRequired(I))
  4487. return false;
  4488. auto *Ptr = getLoadStorePointerOperand(I);
  4489. auto *Ty = getMemInstValueType(I);
  4490. // We have already decided how to vectorize this instruction, get that
  4491. // result.
  4492. if (VF.isVector()) {
  4493. InstWidening WideningDecision = getWideningDecision(I, VF);
  4494. assert(WideningDecision != CM_Unknown &&
  4495. "Widening decision should be ready at this moment");
  4496. return WideningDecision == CM_Scalarize;
  4497. }
  4498. const Align Alignment = getLoadStoreAlignment(I);
  4499. return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
  4500. isLegalMaskedGather(Ty, Alignment))
  4501. : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
  4502. isLegalMaskedScatter(Ty, Alignment));
  4503. }
  4504. case Instruction::UDiv:
  4505. case Instruction::SDiv:
  4506. case Instruction::SRem:
  4507. case Instruction::URem:
  4508. return mayDivideByZero(*I);
  4509. }
  4510. return false;
  4511. }
  4512. bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
  4513. Instruction *I, ElementCount VF) {
  4514. assert(isAccessInterleaved(I) && "Expecting interleaved access.");
  4515. assert(getWideningDecision(I, VF) == CM_Unknown &&
  4516. "Decision should not be set yet.");
  4517. auto *Group = getInterleavedAccessGroup(I);
  4518. assert(Group && "Must have a group.");
  4519. // If the instruction's allocated size doesn't equal it's type size, it
  4520. // requires padding and will be scalarized.
  4521. auto &DL = I->getModule()->getDataLayout();
  4522. auto *ScalarTy = getMemInstValueType(I);
  4523. if (hasIrregularType(ScalarTy, DL))
  4524. return false;
  4525. // Check if masking is required.
  4526. // A Group may need masking for one of two reasons: it resides in a block that
  4527. // needs predication, or it was decided to use masking to deal with gaps.
  4528. bool PredicatedAccessRequiresMasking =
  4529. Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
  4530. bool AccessWithGapsRequiresMasking =
  4531. Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
  4532. if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
  4533. return true;
  4534. // If masked interleaving is required, we expect that the user/target had
  4535. // enabled it, because otherwise it either wouldn't have been created or
  4536. // it should have been invalidated by the CostModel.
  4537. assert(useMaskedInterleavedAccesses(TTI) &&
  4538. "Masked interleave-groups for predicated accesses are not enabled.");
  4539. auto *Ty = getMemInstValueType(I);
  4540. const Align Alignment = getLoadStoreAlignment(I);
  4541. return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
  4542. : TTI.isLegalMaskedStore(Ty, Alignment);
  4543. }
  4544. bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
  4545. Instruction *I, ElementCount VF) {
  4546. // Get and ensure we have a valid memory instruction.
  4547. LoadInst *LI = dyn_cast<LoadInst>(I);
  4548. StoreInst *SI = dyn_cast<StoreInst>(I);
  4549. assert((LI || SI) && "Invalid memory instruction");
  4550. auto *Ptr = getLoadStorePointerOperand(I);
  4551. // In order to be widened, the pointer should be consecutive, first of all.
  4552. if (!Legal->isConsecutivePtr(Ptr))
  4553. return false;
  4554. // If the instruction is a store located in a predicated block, it will be
  4555. // scalarized.
  4556. if (isScalarWithPredication(I))
  4557. return false;
  4558. // If the instruction's allocated size doesn't equal it's type size, it
  4559. // requires padding and will be scalarized.
  4560. auto &DL = I->getModule()->getDataLayout();
  4561. auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
  4562. if (hasIrregularType(ScalarTy, DL))
  4563. return false;
  4564. return true;
  4565. }
  4566. void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
  4567. // We should not collect Uniforms more than once per VF. Right now,
  4568. // this function is called from collectUniformsAndScalars(), which
  4569. // already does this check. Collecting Uniforms for VF=1 does not make any
  4570. // sense.
  4571. assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
  4572. "This function should not be visited twice for the same VF");
  4573. // Visit the list of Uniforms. If we'll not find any uniform value, we'll
  4574. // not analyze again. Uniforms.count(VF) will return 1.
  4575. Uniforms[VF].clear();
  4576. // We now know that the loop is vectorizable!
  4577. // Collect instructions inside the loop that will remain uniform after
  4578. // vectorization.
  4579. // Global values, params and instructions outside of current loop are out of
  4580. // scope.
  4581. auto isOutOfScope = [&](Value *V) -> bool {
  4582. Instruction *I = dyn_cast<Instruction>(V);
  4583. return (!I || !TheLoop->contains(I));
  4584. };
  4585. SetVector<Instruction *> Worklist;
  4586. BasicBlock *Latch = TheLoop->getLoopLatch();
  4587. // Instructions that are scalar with predication must not be considered
  4588. // uniform after vectorization, because that would create an erroneous
  4589. // replicating region where only a single instance out of VF should be formed.
  4590. // TODO: optimize such seldom cases if found important, see PR40816.
  4591. auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
  4592. if (isOutOfScope(I)) {
  4593. LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
  4594. << *I << "\n");
  4595. return;
  4596. }
  4597. if (isScalarWithPredication(I, VF)) {
  4598. LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
  4599. << *I << "\n");
  4600. return;
  4601. }
  4602. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
  4603. Worklist.insert(I);
  4604. };
  4605. // Start with the conditional branch. If the branch condition is an
  4606. // instruction contained in the loop that is only used by the branch, it is
  4607. // uniform.
  4608. auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
  4609. if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
  4610. addToWorklistIfAllowed(Cmp);
  4611. auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
  4612. InstWidening WideningDecision = getWideningDecision(I, VF);
  4613. assert(WideningDecision != CM_Unknown &&
  4614. "Widening decision should be ready at this moment");
  4615. // A uniform memory op is itself uniform. We exclude uniform stores
  4616. // here as they demand the last lane, not the first one.
  4617. if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
  4618. assert(WideningDecision == CM_Scalarize);
  4619. return true;
  4620. }
  4621. return (WideningDecision == CM_Widen ||
  4622. WideningDecision == CM_Widen_Reverse ||
  4623. WideningDecision == CM_Interleave);
  4624. };
  4625. // Returns true if Ptr is the pointer operand of a memory access instruction
  4626. // I, and I is known to not require scalarization.
  4627. auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
  4628. return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
  4629. };
  4630. // Holds a list of values which are known to have at least one uniform use.
  4631. // Note that there may be other uses which aren't uniform. A "uniform use"
  4632. // here is something which only demands lane 0 of the unrolled iterations;
  4633. // it does not imply that all lanes produce the same value (e.g. this is not
  4634. // the usual meaning of uniform)
  4635. SmallPtrSet<Value *, 8> HasUniformUse;
  4636. // Scan the loop for instructions which are either a) known to have only
  4637. // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
  4638. for (auto *BB : TheLoop->blocks())
  4639. for (auto &I : *BB) {
  4640. // If there's no pointer operand, there's nothing to do.
  4641. auto *Ptr = getLoadStorePointerOperand(&I);
  4642. if (!Ptr)
  4643. continue;
  4644. // A uniform memory op is itself uniform. We exclude uniform stores
  4645. // here as they demand the last lane, not the first one.
  4646. if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
  4647. addToWorklistIfAllowed(&I);
  4648. if (isUniformDecision(&I, VF)) {
  4649. assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
  4650. HasUniformUse.insert(Ptr);
  4651. }
  4652. }
  4653. // Add to the worklist any operands which have *only* uniform (e.g. lane 0
  4654. // demanding) users. Since loops are assumed to be in LCSSA form, this
  4655. // disallows uses outside the loop as well.
  4656. for (auto *V : HasUniformUse) {
  4657. if (isOutOfScope(V))
  4658. continue;
  4659. auto *I = cast<Instruction>(V);
  4660. auto UsersAreMemAccesses =
  4661. llvm::all_of(I->users(), [&](User *U) -> bool {
  4662. return isVectorizedMemAccessUse(cast<Instruction>(U), V);
  4663. });
  4664. if (UsersAreMemAccesses)
  4665. addToWorklistIfAllowed(I);
  4666. }
  4667. // Expand Worklist in topological order: whenever a new instruction
  4668. // is added , its users should be already inside Worklist. It ensures
  4669. // a uniform instruction will only be used by uniform instructions.
  4670. unsigned idx = 0;
  4671. while (idx != Worklist.size()) {
  4672. Instruction *I = Worklist[idx++];
  4673. for (auto OV : I->operand_values()) {
  4674. // isOutOfScope operands cannot be uniform instructions.
  4675. if (isOutOfScope(OV))
  4676. continue;
  4677. // First order recurrence Phi's should typically be considered
  4678. // non-uniform.
  4679. auto *OP = dyn_cast<PHINode>(OV);
  4680. if (OP && Legal->isFirstOrderRecurrence(OP))
  4681. continue;
  4682. // If all the users of the operand are uniform, then add the
  4683. // operand into the uniform worklist.
  4684. auto *OI = cast<Instruction>(OV);
  4685. if (llvm::all_of(OI->users(), [&](User *U) -> bool {
  4686. auto *J = cast<Instruction>(U);
  4687. return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
  4688. }))
  4689. addToWorklistIfAllowed(OI);
  4690. }
  4691. }
  4692. // For an instruction to be added into Worklist above, all its users inside
  4693. // the loop should also be in Worklist. However, this condition cannot be
  4694. // true for phi nodes that form a cyclic dependence. We must process phi
  4695. // nodes separately. An induction variable will remain uniform if all users
  4696. // of the induction variable and induction variable update remain uniform.
  4697. // The code below handles both pointer and non-pointer induction variables.
  4698. for (auto &Induction : Legal->getInductionVars()) {
  4699. auto *Ind = Induction.first;
  4700. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  4701. // Determine if all users of the induction variable are uniform after
  4702. // vectorization.
  4703. auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  4704. auto *I = cast<Instruction>(U);
  4705. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
  4706. isVectorizedMemAccessUse(I, Ind);
  4707. });
  4708. if (!UniformInd)
  4709. continue;
  4710. // Determine if all users of the induction variable update instruction are
  4711. // uniform after vectorization.
  4712. auto UniformIndUpdate =
  4713. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  4714. auto *I = cast<Instruction>(U);
  4715. return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
  4716. isVectorizedMemAccessUse(I, IndUpdate);
  4717. });
  4718. if (!UniformIndUpdate)
  4719. continue;
  4720. // The induction variable and its update instruction will remain uniform.
  4721. addToWorklistIfAllowed(Ind);
  4722. addToWorklistIfAllowed(IndUpdate);
  4723. }
  4724. Uniforms[VF].insert(Worklist.begin(), Worklist.end());
  4725. }
  4726. bool LoopVectorizationCostModel::runtimeChecksRequired() {
  4727. LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
  4728. if (Legal->getRuntimePointerChecking()->Need) {
  4729. reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
  4730. "runtime pointer checks needed. Enable vectorization of this "
  4731. "loop with '#pragma clang loop vectorize(enable)' when "
  4732. "compiling with -Os/-Oz",
  4733. "CantVersionLoopWithOptForSize", ORE, TheLoop);
  4734. return true;
  4735. }
  4736. if (!PSE.getUnionPredicate().getPredicates().empty()) {
  4737. reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
  4738. "runtime SCEV checks needed. Enable vectorization of this "
  4739. "loop with '#pragma clang loop vectorize(enable)' when "
  4740. "compiling with -Os/-Oz",
  4741. "CantVersionLoopWithOptForSize", ORE, TheLoop);
  4742. return true;
  4743. }
  4744. // FIXME: Avoid specializing for stride==1 instead of bailing out.
  4745. if (!Legal->getLAI()->getSymbolicStrides().empty()) {
  4746. reportVectorizationFailure("Runtime stride check for small trip count",
  4747. "runtime stride == 1 checks needed. Enable vectorization of "
  4748. "this loop without such check by compiling with -Os/-Oz",
  4749. "CantVersionLoopWithOptForSize", ORE, TheLoop);
  4750. return true;
  4751. }
  4752. return false;
  4753. }
  4754. Optional<ElementCount>
  4755. LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
  4756. if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
  4757. // TODO: It may by useful to do since it's still likely to be dynamically
  4758. // uniform if the target can skip.
  4759. reportVectorizationFailure(
  4760. "Not inserting runtime ptr check for divergent target",
  4761. "runtime pointer checks needed. Not enabled for divergent target",
  4762. "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
  4763. return None;
  4764. }
  4765. unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
  4766. LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
  4767. if (TC == 1) {
  4768. reportVectorizationFailure("Single iteration (non) loop",
  4769. "loop trip count is one, irrelevant for vectorization",
  4770. "SingleIterationLoop", ORE, TheLoop);
  4771. return None;
  4772. }
  4773. switch (ScalarEpilogueStatus) {
  4774. case CM_ScalarEpilogueAllowed:
  4775. return computeFeasibleMaxVF(TC, UserVF);
  4776. case CM_ScalarEpilogueNotAllowedUsePredicate:
  4777. LLVM_FALLTHROUGH;
  4778. case CM_ScalarEpilogueNotNeededUsePredicate:
  4779. LLVM_DEBUG(
  4780. dbgs() << "LV: vector predicate hint/switch found.\n"
  4781. << "LV: Not allowing scalar epilogue, creating predicated "
  4782. << "vector loop.\n");
  4783. break;
  4784. case CM_ScalarEpilogueNotAllowedLowTripLoop:
  4785. // fallthrough as a special case of OptForSize
  4786. case CM_ScalarEpilogueNotAllowedOptSize:
  4787. if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
  4788. LLVM_DEBUG(
  4789. dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
  4790. else
  4791. LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
  4792. << "count.\n");
  4793. // Bail if runtime checks are required, which are not good when optimising
  4794. // for size.
  4795. if (runtimeChecksRequired())
  4796. return None;
  4797. break;
  4798. }
  4799. // The only loops we can vectorize without a scalar epilogue, are loops with
  4800. // a bottom-test and a single exiting block. We'd have to handle the fact
  4801. // that not every instruction executes on the last iteration. This will
  4802. // require a lane mask which varies through the vector loop body. (TODO)
  4803. if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
  4804. // If there was a tail-folding hint/switch, but we can't fold the tail by
  4805. // masking, fallback to a vectorization with a scalar epilogue.
  4806. if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
  4807. LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
  4808. "scalar epilogue instead.\n");
  4809. ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
  4810. return computeFeasibleMaxVF(TC, UserVF);
  4811. }
  4812. return None;
  4813. }
  4814. // Now try the tail folding
  4815. // Invalidate interleave groups that require an epilogue if we can't mask
  4816. // the interleave-group.
  4817. if (!useMaskedInterleavedAccesses(TTI)) {
  4818. assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
  4819. "No decisions should have been taken at this point");
  4820. // Note: There is no need to invalidate any cost modeling decisions here, as
  4821. // non where taken so far.
  4822. InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
  4823. }
  4824. ElementCount MaxVF = computeFeasibleMaxVF(TC, UserVF);
  4825. assert(!MaxVF.isScalable() &&
  4826. "Scalable vectors do not yet support tail folding");
  4827. assert((UserVF.isNonZero() || isPowerOf2_32(MaxVF.getFixedValue())) &&
  4828. "MaxVF must be a power of 2");
  4829. unsigned MaxVFtimesIC =
  4830. UserIC ? MaxVF.getFixedValue() * UserIC : MaxVF.getFixedValue();
  4831. // Avoid tail folding if the trip count is known to be a multiple of any VF we
  4832. // chose.
  4833. ScalarEvolution *SE = PSE.getSE();
  4834. const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
  4835. const SCEV *ExitCount = SE->getAddExpr(
  4836. BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
  4837. const SCEV *Rem = SE->getURemExpr(
  4838. ExitCount, SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
  4839. if (Rem->isZero()) {
  4840. // Accept MaxVF if we do not have a tail.
  4841. LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
  4842. return MaxVF;
  4843. }
  4844. // If we don't know the precise trip count, or if the trip count that we
  4845. // found modulo the vectorization factor is not zero, try to fold the tail
  4846. // by masking.
  4847. // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
  4848. if (Legal->prepareToFoldTailByMasking()) {
  4849. FoldTailByMasking = true;
  4850. return MaxVF;
  4851. }
  4852. // If there was a tail-folding hint/switch, but we can't fold the tail by
  4853. // masking, fallback to a vectorization with a scalar epilogue.
  4854. if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
  4855. LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
  4856. "scalar epilogue instead.\n");
  4857. ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
  4858. return MaxVF;
  4859. }
  4860. if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
  4861. LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
  4862. return None;
  4863. }
  4864. if (TC == 0) {
  4865. reportVectorizationFailure(
  4866. "Unable to calculate the loop count due to complex control flow",
  4867. "unable to calculate the loop count due to complex control flow",
  4868. "UnknownLoopCountComplexCFG", ORE, TheLoop);
  4869. return None;
  4870. }
  4871. reportVectorizationFailure(
  4872. "Cannot optimize for size and vectorize at the same time.",
  4873. "cannot optimize for size and vectorize at the same time. "
  4874. "Enable vectorization of this loop with '#pragma clang loop "
  4875. "vectorize(enable)' when compiling with -Os/-Oz",
  4876. "NoTailLoopWithOptForSize", ORE, TheLoop);
  4877. return None;
  4878. }
  4879. ElementCount
  4880. LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
  4881. ElementCount UserVF) {
  4882. bool IgnoreScalableUserVF = UserVF.isScalable() &&
  4883. !TTI.supportsScalableVectors() &&
  4884. !ForceTargetSupportsScalableVectors;
  4885. if (IgnoreScalableUserVF) {
  4886. LLVM_DEBUG(
  4887. dbgs() << "LV: Ignoring VF=" << UserVF
  4888. << " because target does not support scalable vectors.\n");
  4889. ORE->emit([&]() {
  4890. return OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreScalableUserVF",
  4891. TheLoop->getStartLoc(),
  4892. TheLoop->getHeader())
  4893. << "Ignoring VF=" << ore::NV("UserVF", UserVF)
  4894. << " because target does not support scalable vectors.";
  4895. });
  4896. }
  4897. // Beyond this point two scenarios are handled. If UserVF isn't specified
  4898. // then a suitable VF is chosen. If UserVF is specified and there are
  4899. // dependencies, check if it's legal. However, if a UserVF is specified and
  4900. // there are no dependencies, then there's nothing to do.
  4901. if (UserVF.isNonZero() && !IgnoreScalableUserVF &&
  4902. Legal->isSafeForAnyVectorWidth())
  4903. return UserVF;
  4904. MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
  4905. unsigned SmallestType, WidestType;
  4906. std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
  4907. unsigned WidestRegister = TTI.getRegisterBitWidth(true);
  4908. // Get the maximum safe dependence distance in bits computed by LAA.
  4909. // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
  4910. // the memory accesses that is most restrictive (involved in the smallest
  4911. // dependence distance).
  4912. unsigned MaxSafeVectorWidthInBits = Legal->getMaxSafeVectorWidthInBits();
  4913. // If the user vectorization factor is legally unsafe, clamp it to a safe
  4914. // value. Otherwise, return as is.
  4915. if (UserVF.isNonZero() && !IgnoreScalableUserVF) {
  4916. unsigned MaxSafeElements =
  4917. PowerOf2Floor(MaxSafeVectorWidthInBits / WidestType);
  4918. ElementCount MaxSafeVF = ElementCount::getFixed(MaxSafeElements);
  4919. if (UserVF.isScalable()) {
  4920. Optional<unsigned> MaxVScale = TTI.getMaxVScale();
  4921. // Scale VF by vscale before checking if it's safe.
  4922. MaxSafeVF = ElementCount::getScalable(
  4923. MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
  4924. if (MaxSafeVF.isZero()) {
  4925. // The dependence distance is too small to use scalable vectors,
  4926. // fallback on fixed.
  4927. LLVM_DEBUG(
  4928. dbgs()
  4929. << "LV: Max legal vector width too small, scalable vectorization "
  4930. "unfeasible. Using fixed-width vectorization instead.\n");
  4931. ORE->emit([&]() {
  4932. return OptimizationRemarkAnalysis(DEBUG_TYPE, "ScalableVFUnfeasible",
  4933. TheLoop->getStartLoc(),
  4934. TheLoop->getHeader())
  4935. << "Max legal vector width too small, scalable vectorization "
  4936. << "unfeasible. Using fixed-width vectorization instead.";
  4937. });
  4938. return computeFeasibleMaxVF(
  4939. ConstTripCount, ElementCount::getFixed(UserVF.getKnownMinValue()));
  4940. }
  4941. }
  4942. LLVM_DEBUG(dbgs() << "LV: The max safe VF is: " << MaxSafeVF << ".\n");
  4943. if (ElementCount::isKnownLE(UserVF, MaxSafeVF))
  4944. return UserVF;
  4945. LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
  4946. << " is unsafe, clamping to max safe VF=" << MaxSafeVF
  4947. << ".\n");
  4948. ORE->emit([&]() {
  4949. return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
  4950. TheLoop->getStartLoc(),
  4951. TheLoop->getHeader())
  4952. << "User-specified vectorization factor "
  4953. << ore::NV("UserVectorizationFactor", UserVF)
  4954. << " is unsafe, clamping to maximum safe vectorization factor "
  4955. << ore::NV("VectorizationFactor", MaxSafeVF);
  4956. });
  4957. return MaxSafeVF;
  4958. }
  4959. WidestRegister = std::min(WidestRegister, MaxSafeVectorWidthInBits);
  4960. // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
  4961. // Note that both WidestRegister and WidestType may not be a powers of 2.
  4962. unsigned MaxVectorSize = PowerOf2Floor(WidestRegister / WidestType);
  4963. LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
  4964. << " / " << WidestType << " bits.\n");
  4965. LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
  4966. << WidestRegister << " bits.\n");
  4967. assert(MaxVectorSize <= WidestRegister &&
  4968. "Did not expect to pack so many elements"
  4969. " into one vector!");
  4970. if (MaxVectorSize == 0) {
  4971. LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
  4972. MaxVectorSize = 1;
  4973. return ElementCount::getFixed(MaxVectorSize);
  4974. } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
  4975. isPowerOf2_32(ConstTripCount)) {
  4976. // We need to clamp the VF to be the ConstTripCount. There is no point in
  4977. // choosing a higher viable VF as done in the loop below.
  4978. LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
  4979. << ConstTripCount << "\n");
  4980. MaxVectorSize = ConstTripCount;
  4981. return ElementCount::getFixed(MaxVectorSize);
  4982. }
  4983. unsigned MaxVF = MaxVectorSize;
  4984. if (TTI.shouldMaximizeVectorBandwidth(!isScalarEpilogueAllowed()) ||
  4985. (MaximizeBandwidth && isScalarEpilogueAllowed())) {
  4986. // Collect all viable vectorization factors larger than the default MaxVF
  4987. // (i.e. MaxVectorSize).
  4988. SmallVector<ElementCount, 8> VFs;
  4989. unsigned NewMaxVectorSize = WidestRegister / SmallestType;
  4990. for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
  4991. VFs.push_back(ElementCount::getFixed(VS));
  4992. // For each VF calculate its register usage.
  4993. auto RUs = calculateRegisterUsage(VFs);
  4994. // Select the largest VF which doesn't require more registers than existing
  4995. // ones.
  4996. for (int i = RUs.size() - 1; i >= 0; --i) {
  4997. bool Selected = true;
  4998. for (auto& pair : RUs[i].MaxLocalUsers) {
  4999. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
  5000. if (pair.second > TargetNumRegisters)
  5001. Selected = false;
  5002. }
  5003. if (Selected) {
  5004. MaxVF = VFs[i].getKnownMinValue();
  5005. break;
  5006. }
  5007. }
  5008. if (unsigned MinVF = TTI.getMinimumVF(SmallestType)) {
  5009. if (MaxVF < MinVF) {
  5010. LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
  5011. << ") with target's minimum: " << MinVF << '\n');
  5012. MaxVF = MinVF;
  5013. }
  5014. }
  5015. }
  5016. return ElementCount::getFixed(MaxVF);
  5017. }
  5018. VectorizationFactor
  5019. LoopVectorizationCostModel::selectVectorizationFactor(ElementCount MaxVF) {
  5020. // FIXME: This can be fixed for scalable vectors later, because at this stage
  5021. // the LoopVectorizer will only consider vectorizing a loop with scalable
  5022. // vectors when the loop has a hint to enable vectorization for a given VF.
  5023. assert(!MaxVF.isScalable() && "scalable vectors not yet supported");
  5024. InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
  5025. LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
  5026. assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
  5027. unsigned Width = 1;
  5028. const float ScalarCost = *ExpectedCost.getValue();
  5029. float Cost = ScalarCost;
  5030. bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
  5031. if (ForceVectorization && MaxVF.isVector()) {
  5032. // Ignore scalar width, because the user explicitly wants vectorization.
  5033. // Initialize cost to max so that VF = 2 is, at least, chosen during cost
  5034. // evaluation.
  5035. Cost = std::numeric_limits<float>::max();
  5036. }
  5037. for (unsigned i = 2; i <= MaxVF.getFixedValue(); i *= 2) {
  5038. // Notice that the vector loop needs to be executed less times, so
  5039. // we need to divide the cost of the vector loops by the width of
  5040. // the vector elements.
  5041. VectorizationCostTy C = expectedCost(ElementCount::getFixed(i));
  5042. assert(C.first.isValid() && "Unexpected invalid cost for vector loop");
  5043. float VectorCost = *C.first.getValue() / (float)i;
  5044. LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
  5045. << " costs: " << (int)VectorCost << ".\n");
  5046. if (!C.second && !ForceVectorization) {
  5047. LLVM_DEBUG(
  5048. dbgs() << "LV: Not considering vector loop of width " << i
  5049. << " because it will not generate any vector instructions.\n");
  5050. continue;
  5051. }
  5052. // If profitable add it to ProfitableVF list.
  5053. if (VectorCost < ScalarCost) {
  5054. ProfitableVFs.push_back(VectorizationFactor(
  5055. {ElementCount::getFixed(i), (unsigned)VectorCost}));
  5056. }
  5057. if (VectorCost < Cost) {
  5058. Cost = VectorCost;
  5059. Width = i;
  5060. }
  5061. }
  5062. if (!EnableCondStoresVectorization && NumPredStores) {
  5063. reportVectorizationFailure("There are conditional stores.",
  5064. "store that is conditionally executed prevents vectorization",
  5065. "ConditionalStore", ORE, TheLoop);
  5066. Width = 1;
  5067. Cost = ScalarCost;
  5068. }
  5069. LLVM_DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
  5070. << "LV: Vectorization seems to be not beneficial, "
  5071. << "but was forced by a user.\n");
  5072. LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
  5073. VectorizationFactor Factor = {ElementCount::getFixed(Width),
  5074. (unsigned)(Width * Cost)};
  5075. return Factor;
  5076. }
  5077. bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
  5078. const Loop &L, ElementCount VF) const {
  5079. // Cross iteration phis such as reductions need special handling and are
  5080. // currently unsupported.
  5081. if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
  5082. return Legal->isFirstOrderRecurrence(&Phi) ||
  5083. Legal->isReductionVariable(&Phi);
  5084. }))
  5085. return false;
  5086. // Phis with uses outside of the loop require special handling and are
  5087. // currently unsupported.
  5088. for (auto &Entry : Legal->getInductionVars()) {
  5089. // Look for uses of the value of the induction at the last iteration.
  5090. Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
  5091. for (User *U : PostInc->users())
  5092. if (!L.contains(cast<Instruction>(U)))
  5093. return false;
  5094. // Look for uses of penultimate value of the induction.
  5095. for (User *U : Entry.first->users())
  5096. if (!L.contains(cast<Instruction>(U)))
  5097. return false;
  5098. }
  5099. // Induction variables that are widened require special handling that is
  5100. // currently not supported.
  5101. if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
  5102. return !(this->isScalarAfterVectorization(Entry.first, VF) ||
  5103. this->isProfitableToScalarize(Entry.first, VF));
  5104. }))
  5105. return false;
  5106. return true;
  5107. }
  5108. bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
  5109. const ElementCount VF) const {
  5110. // FIXME: We need a much better cost-model to take different parameters such
  5111. // as register pressure, code size increase and cost of extra branches into
  5112. // account. For now we apply a very crude heuristic and only consider loops
  5113. // with vectorization factors larger than a certain value.
  5114. // We also consider epilogue vectorization unprofitable for targets that don't
  5115. // consider interleaving beneficial (eg. MVE).
  5116. if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
  5117. return false;
  5118. if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
  5119. return true;
  5120. return false;
  5121. }
  5122. VectorizationFactor
  5123. LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
  5124. const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
  5125. VectorizationFactor Result = VectorizationFactor::Disabled();
  5126. if (!EnableEpilogueVectorization) {
  5127. LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
  5128. return Result;
  5129. }
  5130. if (!isScalarEpilogueAllowed()) {
  5131. LLVM_DEBUG(
  5132. dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
  5133. "allowed.\n";);
  5134. return Result;
  5135. }
  5136. // FIXME: This can be fixed for scalable vectors later, because at this stage
  5137. // the LoopVectorizer will only consider vectorizing a loop with scalable
  5138. // vectors when the loop has a hint to enable vectorization for a given VF.
  5139. if (MainLoopVF.isScalable()) {
  5140. LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization for scalable vectors not "
  5141. "yet supported.\n");
  5142. return Result;
  5143. }
  5144. // Not really a cost consideration, but check for unsupported cases here to
  5145. // simplify the logic.
  5146. if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
  5147. LLVM_DEBUG(
  5148. dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
  5149. "not a supported candidate.\n";);
  5150. return Result;
  5151. }
  5152. if (EpilogueVectorizationForceVF > 1) {
  5153. LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
  5154. if (LVP.hasPlanWithVFs(
  5155. {MainLoopVF, ElementCount::getFixed(EpilogueVectorizationForceVF)}))
  5156. return {ElementCount::getFixed(EpilogueVectorizationForceVF), 0};
  5157. else {
  5158. LLVM_DEBUG(
  5159. dbgs()
  5160. << "LEV: Epilogue vectorization forced factor is not viable.\n";);
  5161. return Result;
  5162. }
  5163. }
  5164. if (TheLoop->getHeader()->getParent()->hasOptSize() ||
  5165. TheLoop->getHeader()->getParent()->hasMinSize()) {
  5166. LLVM_DEBUG(
  5167. dbgs()
  5168. << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
  5169. return Result;
  5170. }
  5171. if (!isEpilogueVectorizationProfitable(MainLoopVF))
  5172. return Result;
  5173. for (auto &NextVF : ProfitableVFs)
  5174. if (ElementCount::isKnownLT(NextVF.Width, MainLoopVF) &&
  5175. (Result.Width.getFixedValue() == 1 || NextVF.Cost < Result.Cost) &&
  5176. LVP.hasPlanWithVFs({MainLoopVF, NextVF.Width}))
  5177. Result = NextVF;
  5178. if (Result != VectorizationFactor::Disabled())
  5179. LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
  5180. << Result.Width.getFixedValue() << "\n";);
  5181. return Result;
  5182. }
  5183. std::pair<unsigned, unsigned>
  5184. LoopVectorizationCostModel::getSmallestAndWidestTypes() {
  5185. unsigned MinWidth = -1U;
  5186. unsigned MaxWidth = 8;
  5187. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  5188. // For each block.
  5189. for (BasicBlock *BB : TheLoop->blocks()) {
  5190. // For each instruction in the loop.
  5191. for (Instruction &I : BB->instructionsWithoutDebug()) {
  5192. Type *T = I.getType();
  5193. // Skip ignored values.
  5194. if (ValuesToIgnore.count(&I))
  5195. continue;
  5196. // Only examine Loads, Stores and PHINodes.
  5197. if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
  5198. continue;
  5199. // Examine PHI nodes that are reduction variables. Update the type to
  5200. // account for the recurrence type.
  5201. if (auto *PN = dyn_cast<PHINode>(&I)) {
  5202. if (!Legal->isReductionVariable(PN))
  5203. continue;
  5204. RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[PN];
  5205. if (PreferInLoopReductions ||
  5206. TTI.preferInLoopReduction(RdxDesc.getOpcode(),
  5207. RdxDesc.getRecurrenceType(),
  5208. TargetTransformInfo::ReductionFlags()))
  5209. continue;
  5210. T = RdxDesc.getRecurrenceType();
  5211. }
  5212. // Examine the stored values.
  5213. if (auto *ST = dyn_cast<StoreInst>(&I))
  5214. T = ST->getValueOperand()->getType();
  5215. // Ignore loaded pointer types and stored pointer types that are not
  5216. // vectorizable.
  5217. //
  5218. // FIXME: The check here attempts to predict whether a load or store will
  5219. // be vectorized. We only know this for certain after a VF has
  5220. // been selected. Here, we assume that if an access can be
  5221. // vectorized, it will be. We should also look at extending this
  5222. // optimization to non-pointer types.
  5223. //
  5224. if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
  5225. !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
  5226. continue;
  5227. MinWidth = std::min(MinWidth,
  5228. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  5229. MaxWidth = std::max(MaxWidth,
  5230. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  5231. }
  5232. }
  5233. return {MinWidth, MaxWidth};
  5234. }
  5235. unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
  5236. unsigned LoopCost) {
  5237. // -- The interleave heuristics --
  5238. // We interleave the loop in order to expose ILP and reduce the loop overhead.
  5239. // There are many micro-architectural considerations that we can't predict
  5240. // at this level. For example, frontend pressure (on decode or fetch) due to
  5241. // code size, or the number and capabilities of the execution ports.
  5242. //
  5243. // We use the following heuristics to select the interleave count:
  5244. // 1. If the code has reductions, then we interleave to break the cross
  5245. // iteration dependency.
  5246. // 2. If the loop is really small, then we interleave to reduce the loop
  5247. // overhead.
  5248. // 3. We don't interleave if we think that we will spill registers to memory
  5249. // due to the increased register pressure.
  5250. if (!isScalarEpilogueAllowed())
  5251. return 1;
  5252. // We used the distance for the interleave count.
  5253. if (Legal->getMaxSafeDepDistBytes() != -1U)
  5254. return 1;
  5255. auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
  5256. const bool HasReductions = !Legal->getReductionVars().empty();
  5257. // Do not interleave loops with a relatively small known or estimated trip
  5258. // count. But we will interleave when InterleaveSmallLoopScalarReduction is
  5259. // enabled, and the code has scalar reductions(HasReductions && VF = 1),
  5260. // because with the above conditions interleaving can expose ILP and break
  5261. // cross iteration dependences for reductions.
  5262. if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
  5263. !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
  5264. return 1;
  5265. RegisterUsage R = calculateRegisterUsage({VF})[0];
  5266. // We divide by these constants so assume that we have at least one
  5267. // instruction that uses at least one register.
  5268. for (auto& pair : R.MaxLocalUsers) {
  5269. pair.second = std::max(pair.second, 1U);
  5270. }
  5271. // We calculate the interleave count using the following formula.
  5272. // Subtract the number of loop invariants from the number of available
  5273. // registers. These registers are used by all of the interleaved instances.
  5274. // Next, divide the remaining registers by the number of registers that is
  5275. // required by the loop, in order to estimate how many parallel instances
  5276. // fit without causing spills. All of this is rounded down if necessary to be
  5277. // a power of two. We want power of two interleave count to simplify any
  5278. // addressing operations or alignment considerations.
  5279. // We also want power of two interleave counts to ensure that the induction
  5280. // variable of the vector loop wraps to zero, when tail is folded by masking;
  5281. // this currently happens when OptForSize, in which case IC is set to 1 above.
  5282. unsigned IC = UINT_MAX;
  5283. for (auto& pair : R.MaxLocalUsers) {
  5284. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
  5285. LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
  5286. << " registers of "
  5287. << TTI.getRegisterClassName(pair.first) << " register class\n");
  5288. if (VF.isScalar()) {
  5289. if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
  5290. TargetNumRegisters = ForceTargetNumScalarRegs;
  5291. } else {
  5292. if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
  5293. TargetNumRegisters = ForceTargetNumVectorRegs;
  5294. }
  5295. unsigned MaxLocalUsers = pair.second;
  5296. unsigned LoopInvariantRegs = 0;
  5297. if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
  5298. LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
  5299. unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
  5300. // Don't count the induction variable as interleaved.
  5301. if (EnableIndVarRegisterHeur) {
  5302. TmpIC =
  5303. PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
  5304. std::max(1U, (MaxLocalUsers - 1)));
  5305. }
  5306. IC = std::min(IC, TmpIC);
  5307. }
  5308. // Clamp the interleave ranges to reasonable counts.
  5309. unsigned MaxInterleaveCount =
  5310. TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
  5311. // Check if the user has overridden the max.
  5312. if (VF.isScalar()) {
  5313. if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
  5314. MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
  5315. } else {
  5316. if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
  5317. MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
  5318. }
  5319. // If trip count is known or estimated compile time constant, limit the
  5320. // interleave count to be less than the trip count divided by VF, provided it
  5321. // is at least 1.
  5322. //
  5323. // For scalable vectors we can't know if interleaving is beneficial. It may
  5324. // not be beneficial for small loops if none of the lanes in the second vector
  5325. // iterations is enabled. However, for larger loops, there is likely to be a
  5326. // similar benefit as for fixed-width vectors. For now, we choose to leave
  5327. // the InterleaveCount as if vscale is '1', although if some information about
  5328. // the vector is known (e.g. min vector size), we can make a better decision.
  5329. if (BestKnownTC) {
  5330. MaxInterleaveCount =
  5331. std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
  5332. // Make sure MaxInterleaveCount is greater than 0.
  5333. MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
  5334. }
  5335. assert(MaxInterleaveCount > 0 &&
  5336. "Maximum interleave count must be greater than 0");
  5337. // Clamp the calculated IC to be between the 1 and the max interleave count
  5338. // that the target and trip count allows.
  5339. if (IC > MaxInterleaveCount)
  5340. IC = MaxInterleaveCount;
  5341. else
  5342. // Make sure IC is greater than 0.
  5343. IC = std::max(1u, IC);
  5344. assert(IC > 0 && "Interleave count must be greater than 0.");
  5345. // If we did not calculate the cost for VF (because the user selected the VF)
  5346. // then we calculate the cost of VF here.
  5347. if (LoopCost == 0) {
  5348. assert(expectedCost(VF).first.isValid() && "Expected a valid cost");
  5349. LoopCost = *expectedCost(VF).first.getValue();
  5350. }
  5351. assert(LoopCost && "Non-zero loop cost expected");
  5352. // Interleave if we vectorized this loop and there is a reduction that could
  5353. // benefit from interleaving.
  5354. if (VF.isVector() && HasReductions) {
  5355. LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
  5356. return IC;
  5357. }
  5358. // Note that if we've already vectorized the loop we will have done the
  5359. // runtime check and so interleaving won't require further checks.
  5360. bool InterleavingRequiresRuntimePointerCheck =
  5361. (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
  5362. // We want to interleave small loops in order to reduce the loop overhead and
  5363. // potentially expose ILP opportunities.
  5364. LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
  5365. << "LV: IC is " << IC << '\n'
  5366. << "LV: VF is " << VF << '\n');
  5367. const bool AggressivelyInterleaveReductions =
  5368. TTI.enableAggressiveInterleaving(HasReductions);
  5369. if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
  5370. // We assume that the cost overhead is 1 and we use the cost model
  5371. // to estimate the cost of the loop and interleave until the cost of the
  5372. // loop overhead is about 5% of the cost of the loop.
  5373. unsigned SmallIC =
  5374. std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
  5375. // Interleave until store/load ports (estimated by max interleave count) are
  5376. // saturated.
  5377. unsigned NumStores = Legal->getNumStores();
  5378. unsigned NumLoads = Legal->getNumLoads();
  5379. unsigned StoresIC = IC / (NumStores ? NumStores : 1);
  5380. unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
  5381. // If we have a scalar reduction (vector reductions are already dealt with
  5382. // by this point), we can increase the critical path length if the loop
  5383. // we're interleaving is inside another loop. Limit, by default to 2, so the
  5384. // critical path only gets increased by one reduction operation.
  5385. if (HasReductions && TheLoop->getLoopDepth() > 1) {
  5386. unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
  5387. SmallIC = std::min(SmallIC, F);
  5388. StoresIC = std::min(StoresIC, F);
  5389. LoadsIC = std::min(LoadsIC, F);
  5390. }
  5391. if (EnableLoadStoreRuntimeInterleave &&
  5392. std::max(StoresIC, LoadsIC) > SmallIC) {
  5393. LLVM_DEBUG(
  5394. dbgs() << "LV: Interleaving to saturate store or load ports.\n");
  5395. return std::max(StoresIC, LoadsIC);
  5396. }
  5397. // If there are scalar reductions and TTI has enabled aggressive
  5398. // interleaving for reductions, we will interleave to expose ILP.
  5399. if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
  5400. AggressivelyInterleaveReductions) {
  5401. LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
  5402. // Interleave no less than SmallIC but not as aggressive as the normal IC
  5403. // to satisfy the rare situation when resources are too limited.
  5404. return std::max(IC / 2, SmallIC);
  5405. } else {
  5406. LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
  5407. return SmallIC;
  5408. }
  5409. }
  5410. // Interleave if this is a large loop (small loops are already dealt with by
  5411. // this point) that could benefit from interleaving.
  5412. if (AggressivelyInterleaveReductions) {
  5413. LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
  5414. return IC;
  5415. }
  5416. LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
  5417. return 1;
  5418. }
  5419. SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
  5420. LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
  5421. // This function calculates the register usage by measuring the highest number
  5422. // of values that are alive at a single location. Obviously, this is a very
  5423. // rough estimation. We scan the loop in a topological order in order and
  5424. // assign a number to each instruction. We use RPO to ensure that defs are
  5425. // met before their users. We assume that each instruction that has in-loop
  5426. // users starts an interval. We record every time that an in-loop value is
  5427. // used, so we have a list of the first and last occurrences of each
  5428. // instruction. Next, we transpose this data structure into a multi map that
  5429. // holds the list of intervals that *end* at a specific location. This multi
  5430. // map allows us to perform a linear search. We scan the instructions linearly
  5431. // and record each time that a new interval starts, by placing it in a set.
  5432. // If we find this value in the multi-map then we remove it from the set.
  5433. // The max register usage is the maximum size of the set.
  5434. // We also search for instructions that are defined outside the loop, but are
  5435. // used inside the loop. We need this number separately from the max-interval
  5436. // usage number because when we unroll, loop-invariant values do not take
  5437. // more register.
  5438. LoopBlocksDFS DFS(TheLoop);
  5439. DFS.perform(LI);
  5440. RegisterUsage RU;
  5441. // Each 'key' in the map opens a new interval. The values
  5442. // of the map are the index of the 'last seen' usage of the
  5443. // instruction that is the key.
  5444. using IntervalMap = DenseMap<Instruction *, unsigned>;
  5445. // Maps instruction to its index.
  5446. SmallVector<Instruction *, 64> IdxToInstr;
  5447. // Marks the end of each interval.
  5448. IntervalMap EndPoint;
  5449. // Saves the list of instruction indices that are used in the loop.
  5450. SmallPtrSet<Instruction *, 8> Ends;
  5451. // Saves the list of values that are used in the loop but are
  5452. // defined outside the loop, such as arguments and constants.
  5453. SmallPtrSet<Value *, 8> LoopInvariants;
  5454. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  5455. for (Instruction &I : BB->instructionsWithoutDebug()) {
  5456. IdxToInstr.push_back(&I);
  5457. // Save the end location of each USE.
  5458. for (Value *U : I.operands()) {
  5459. auto *Instr = dyn_cast<Instruction>(U);
  5460. // Ignore non-instruction values such as arguments, constants, etc.
  5461. if (!Instr)
  5462. continue;
  5463. // If this instruction is outside the loop then record it and continue.
  5464. if (!TheLoop->contains(Instr)) {
  5465. LoopInvariants.insert(Instr);
  5466. continue;
  5467. }
  5468. // Overwrite previous end points.
  5469. EndPoint[Instr] = IdxToInstr.size();
  5470. Ends.insert(Instr);
  5471. }
  5472. }
  5473. }
  5474. // Saves the list of intervals that end with the index in 'key'.
  5475. using InstrList = SmallVector<Instruction *, 2>;
  5476. DenseMap<unsigned, InstrList> TransposeEnds;
  5477. // Transpose the EndPoints to a list of values that end at each index.
  5478. for (auto &Interval : EndPoint)
  5479. TransposeEnds[Interval.second].push_back(Interval.first);
  5480. SmallPtrSet<Instruction *, 8> OpenIntervals;
  5481. SmallVector<RegisterUsage, 8> RUs(VFs.size());
  5482. SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
  5483. LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
  5484. // A lambda that gets the register usage for the given type and VF.
  5485. const auto &TTICapture = TTI;
  5486. auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) {
  5487. if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
  5488. return 0U;
  5489. return TTICapture.getRegUsageForType(VectorType::get(Ty, VF));
  5490. };
  5491. for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
  5492. Instruction *I = IdxToInstr[i];
  5493. // Remove all of the instructions that end at this location.
  5494. InstrList &List = TransposeEnds[i];
  5495. for (Instruction *ToRemove : List)
  5496. OpenIntervals.erase(ToRemove);
  5497. // Ignore instructions that are never used within the loop.
  5498. if (!Ends.count(I))
  5499. continue;
  5500. // Skip ignored values.
  5501. if (ValuesToIgnore.count(I))
  5502. continue;
  5503. // For each VF find the maximum usage of registers.
  5504. for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
  5505. // Count the number of live intervals.
  5506. SmallMapVector<unsigned, unsigned, 4> RegUsage;
  5507. if (VFs[j].isScalar()) {
  5508. for (auto Inst : OpenIntervals) {
  5509. unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
  5510. if (RegUsage.find(ClassID) == RegUsage.end())
  5511. RegUsage[ClassID] = 1;
  5512. else
  5513. RegUsage[ClassID] += 1;
  5514. }
  5515. } else {
  5516. collectUniformsAndScalars(VFs[j]);
  5517. for (auto Inst : OpenIntervals) {
  5518. // Skip ignored values for VF > 1.
  5519. if (VecValuesToIgnore.count(Inst))
  5520. continue;
  5521. if (isScalarAfterVectorization(Inst, VFs[j])) {
  5522. unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
  5523. if (RegUsage.find(ClassID) == RegUsage.end())
  5524. RegUsage[ClassID] = 1;
  5525. else
  5526. RegUsage[ClassID] += 1;
  5527. } else {
  5528. unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
  5529. if (RegUsage.find(ClassID) == RegUsage.end())
  5530. RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
  5531. else
  5532. RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
  5533. }
  5534. }
  5535. }
  5536. for (auto& pair : RegUsage) {
  5537. if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
  5538. MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
  5539. else
  5540. MaxUsages[j][pair.first] = pair.second;
  5541. }
  5542. }
  5543. LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
  5544. << OpenIntervals.size() << '\n');
  5545. // Add the current instruction to the list of open intervals.
  5546. OpenIntervals.insert(I);
  5547. }
  5548. for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
  5549. SmallMapVector<unsigned, unsigned, 4> Invariant;
  5550. for (auto Inst : LoopInvariants) {
  5551. unsigned Usage =
  5552. VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
  5553. unsigned ClassID =
  5554. TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
  5555. if (Invariant.find(ClassID) == Invariant.end())
  5556. Invariant[ClassID] = Usage;
  5557. else
  5558. Invariant[ClassID] += Usage;
  5559. }
  5560. LLVM_DEBUG({
  5561. dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
  5562. dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
  5563. << " item\n";
  5564. for (const auto &pair : MaxUsages[i]) {
  5565. dbgs() << "LV(REG): RegisterClass: "
  5566. << TTI.getRegisterClassName(pair.first) << ", " << pair.second
  5567. << " registers\n";
  5568. }
  5569. dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
  5570. << " item\n";
  5571. for (const auto &pair : Invariant) {
  5572. dbgs() << "LV(REG): RegisterClass: "
  5573. << TTI.getRegisterClassName(pair.first) << ", " << pair.second
  5574. << " registers\n";
  5575. }
  5576. });
  5577. RU.LoopInvariantRegs = Invariant;
  5578. RU.MaxLocalUsers = MaxUsages[i];
  5579. RUs[i] = RU;
  5580. }
  5581. return RUs;
  5582. }
  5583. bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
  5584. // TODO: Cost model for emulated masked load/store is completely
  5585. // broken. This hack guides the cost model to use an artificially
  5586. // high enough value to practically disable vectorization with such
  5587. // operations, except where previously deployed legality hack allowed
  5588. // using very low cost values. This is to avoid regressions coming simply
  5589. // from moving "masked load/store" check from legality to cost model.
  5590. // Masked Load/Gather emulation was previously never allowed.
  5591. // Limited number of Masked Store/Scatter emulation was allowed.
  5592. assert(isPredicatedInst(I) && "Expecting a scalar emulated instruction");
  5593. return isa<LoadInst>(I) ||
  5594. (isa<StoreInst>(I) &&
  5595. NumPredStores > NumberOfStoresToPredicate);
  5596. }
  5597. void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
  5598. // If we aren't vectorizing the loop, or if we've already collected the
  5599. // instructions to scalarize, there's nothing to do. Collection may already
  5600. // have occurred if we have a user-selected VF and are now computing the
  5601. // expected cost for interleaving.
  5602. if (VF.isScalar() || VF.isZero() ||
  5603. InstsToScalarize.find(VF) != InstsToScalarize.end())
  5604. return;
  5605. // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
  5606. // not profitable to scalarize any instructions, the presence of VF in the
  5607. // map will indicate that we've analyzed it already.
  5608. ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
  5609. // Find all the instructions that are scalar with predication in the loop and
  5610. // determine if it would be better to not if-convert the blocks they are in.
  5611. // If so, we also record the instructions to scalarize.
  5612. for (BasicBlock *BB : TheLoop->blocks()) {
  5613. if (!blockNeedsPredication(BB))
  5614. continue;
  5615. for (Instruction &I : *BB)
  5616. if (isScalarWithPredication(&I)) {
  5617. ScalarCostsTy ScalarCosts;
  5618. // Do not apply discount logic if hacked cost is needed
  5619. // for emulated masked memrefs.
  5620. if (!useEmulatedMaskMemRefHack(&I) &&
  5621. computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
  5622. ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
  5623. // Remember that BB will remain after vectorization.
  5624. PredicatedBBsAfterVectorization.insert(BB);
  5625. }
  5626. }
  5627. }
  5628. int LoopVectorizationCostModel::computePredInstDiscount(
  5629. Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
  5630. assert(!isUniformAfterVectorization(PredInst, VF) &&
  5631. "Instruction marked uniform-after-vectorization will be predicated");
  5632. // Initialize the discount to zero, meaning that the scalar version and the
  5633. // vector version cost the same.
  5634. InstructionCost Discount = 0;
  5635. // Holds instructions to analyze. The instructions we visit are mapped in
  5636. // ScalarCosts. Those instructions are the ones that would be scalarized if
  5637. // we find that the scalar version costs less.
  5638. SmallVector<Instruction *, 8> Worklist;
  5639. // Returns true if the given instruction can be scalarized.
  5640. auto canBeScalarized = [&](Instruction *I) -> bool {
  5641. // We only attempt to scalarize instructions forming a single-use chain
  5642. // from the original predicated block that would otherwise be vectorized.
  5643. // Although not strictly necessary, we give up on instructions we know will
  5644. // already be scalar to avoid traversing chains that are unlikely to be
  5645. // beneficial.
  5646. if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
  5647. isScalarAfterVectorization(I, VF))
  5648. return false;
  5649. // If the instruction is scalar with predication, it will be analyzed
  5650. // separately. We ignore it within the context of PredInst.
  5651. if (isScalarWithPredication(I))
  5652. return false;
  5653. // If any of the instruction's operands are uniform after vectorization,
  5654. // the instruction cannot be scalarized. This prevents, for example, a
  5655. // masked load from being scalarized.
  5656. //
  5657. // We assume we will only emit a value for lane zero of an instruction
  5658. // marked uniform after vectorization, rather than VF identical values.
  5659. // Thus, if we scalarize an instruction that uses a uniform, we would
  5660. // create uses of values corresponding to the lanes we aren't emitting code
  5661. // for. This behavior can be changed by allowing getScalarValue to clone
  5662. // the lane zero values for uniforms rather than asserting.
  5663. for (Use &U : I->operands())
  5664. if (auto *J = dyn_cast<Instruction>(U.get()))
  5665. if (isUniformAfterVectorization(J, VF))
  5666. return false;
  5667. // Otherwise, we can scalarize the instruction.
  5668. return true;
  5669. };
  5670. // Compute the expected cost discount from scalarizing the entire expression
  5671. // feeding the predicated instruction. We currently only consider expressions
  5672. // that are single-use instruction chains.
  5673. Worklist.push_back(PredInst);
  5674. while (!Worklist.empty()) {
  5675. Instruction *I = Worklist.pop_back_val();
  5676. // If we've already analyzed the instruction, there's nothing to do.
  5677. if (ScalarCosts.find(I) != ScalarCosts.end())
  5678. continue;
  5679. // Compute the cost of the vector instruction. Note that this cost already
  5680. // includes the scalarization overhead of the predicated instruction.
  5681. InstructionCost VectorCost = getInstructionCost(I, VF).first;
  5682. // Compute the cost of the scalarized instruction. This cost is the cost of
  5683. // the instruction as if it wasn't if-converted and instead remained in the
  5684. // predicated block. We will scale this cost by block probability after
  5685. // computing the scalarization overhead.
  5686. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  5687. InstructionCost ScalarCost =
  5688. VF.getKnownMinValue() *
  5689. getInstructionCost(I, ElementCount::getFixed(1)).first;
  5690. // Compute the scalarization overhead of needed insertelement instructions
  5691. // and phi nodes.
  5692. if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
  5693. ScalarCost += TTI.getScalarizationOverhead(
  5694. cast<VectorType>(ToVectorTy(I->getType(), VF)),
  5695. APInt::getAllOnesValue(VF.getKnownMinValue()), true, false);
  5696. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  5697. ScalarCost +=
  5698. VF.getKnownMinValue() *
  5699. TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
  5700. }
  5701. // Compute the scalarization overhead of needed extractelement
  5702. // instructions. For each of the instruction's operands, if the operand can
  5703. // be scalarized, add it to the worklist; otherwise, account for the
  5704. // overhead.
  5705. for (Use &U : I->operands())
  5706. if (auto *J = dyn_cast<Instruction>(U.get())) {
  5707. assert(VectorType::isValidElementType(J->getType()) &&
  5708. "Instruction has non-scalar type");
  5709. if (canBeScalarized(J))
  5710. Worklist.push_back(J);
  5711. else if (needsExtract(J, VF)) {
  5712. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  5713. ScalarCost += TTI.getScalarizationOverhead(
  5714. cast<VectorType>(ToVectorTy(J->getType(), VF)),
  5715. APInt::getAllOnesValue(VF.getKnownMinValue()), false, true);
  5716. }
  5717. }
  5718. // Scale the total scalar cost by block probability.
  5719. ScalarCost /= getReciprocalPredBlockProb();
  5720. // Compute the discount. A non-negative discount means the vector version
  5721. // of the instruction costs more, and scalarizing would be beneficial.
  5722. Discount += VectorCost - ScalarCost;
  5723. ScalarCosts[I] = ScalarCost;
  5724. }
  5725. return *Discount.getValue();
  5726. }
  5727. LoopVectorizationCostModel::VectorizationCostTy
  5728. LoopVectorizationCostModel::expectedCost(ElementCount VF) {
  5729. VectorizationCostTy Cost;
  5730. // For each block.
  5731. for (BasicBlock *BB : TheLoop->blocks()) {
  5732. VectorizationCostTy BlockCost;
  5733. // For each instruction in the old loop.
  5734. for (Instruction &I : BB->instructionsWithoutDebug()) {
  5735. // Skip ignored values.
  5736. if (ValuesToIgnore.count(&I) ||
  5737. (VF.isVector() && VecValuesToIgnore.count(&I)))
  5738. continue;
  5739. VectorizationCostTy C = getInstructionCost(&I, VF);
  5740. // Check if we should override the cost.
  5741. if (ForceTargetInstructionCost.getNumOccurrences() > 0)
  5742. C.first = InstructionCost(ForceTargetInstructionCost);
  5743. BlockCost.first += C.first;
  5744. BlockCost.second |= C.second;
  5745. LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
  5746. << " for VF " << VF << " For instruction: " << I
  5747. << '\n');
  5748. }
  5749. // If we are vectorizing a predicated block, it will have been
  5750. // if-converted. This means that the block's instructions (aside from
  5751. // stores and instructions that may divide by zero) will now be
  5752. // unconditionally executed. For the scalar case, we may not always execute
  5753. // the predicated block, if it is an if-else block. Thus, scale the block's
  5754. // cost by the probability of executing it. blockNeedsPredication from
  5755. // Legal is used so as to not include all blocks in tail folded loops.
  5756. if (VF.isScalar() && Legal->blockNeedsPredication(BB))
  5757. BlockCost.first /= getReciprocalPredBlockProb();
  5758. Cost.first += BlockCost.first;
  5759. Cost.second |= BlockCost.second;
  5760. }
  5761. return Cost;
  5762. }
  5763. /// Gets Address Access SCEV after verifying that the access pattern
  5764. /// is loop invariant except the induction variable dependence.
  5765. ///
  5766. /// This SCEV can be sent to the Target in order to estimate the address
  5767. /// calculation cost.
  5768. static const SCEV *getAddressAccessSCEV(
  5769. Value *Ptr,
  5770. LoopVectorizationLegality *Legal,
  5771. PredicatedScalarEvolution &PSE,
  5772. const Loop *TheLoop) {
  5773. auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  5774. if (!Gep)
  5775. return nullptr;
  5776. // We are looking for a gep with all loop invariant indices except for one
  5777. // which should be an induction variable.
  5778. auto SE = PSE.getSE();
  5779. unsigned NumOperands = Gep->getNumOperands();
  5780. for (unsigned i = 1; i < NumOperands; ++i) {
  5781. Value *Opd = Gep->getOperand(i);
  5782. if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
  5783. !Legal->isInductionVariable(Opd))
  5784. return nullptr;
  5785. }
  5786. // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
  5787. return PSE.getSCEV(Ptr);
  5788. }
  5789. static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
  5790. return Legal->hasStride(I->getOperand(0)) ||
  5791. Legal->hasStride(I->getOperand(1));
  5792. }
  5793. InstructionCost
  5794. LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
  5795. ElementCount VF) {
  5796. assert(VF.isVector() &&
  5797. "Scalarization cost of instruction implies vectorization.");
  5798. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  5799. Type *ValTy = getMemInstValueType(I);
  5800. auto SE = PSE.getSE();
  5801. unsigned AS = getLoadStoreAddressSpace(I);
  5802. Value *Ptr = getLoadStorePointerOperand(I);
  5803. Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
  5804. // Figure out whether the access is strided and get the stride value
  5805. // if it's known in compile time
  5806. const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
  5807. // Get the cost of the scalar memory instruction and address computation.
  5808. InstructionCost Cost =
  5809. VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
  5810. // Don't pass *I here, since it is scalar but will actually be part of a
  5811. // vectorized loop where the user of it is a vectorized instruction.
  5812. const Align Alignment = getLoadStoreAlignment(I);
  5813. Cost += VF.getKnownMinValue() *
  5814. TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
  5815. AS, TTI::TCK_RecipThroughput);
  5816. // Get the overhead of the extractelement and insertelement instructions
  5817. // we might create due to scalarization.
  5818. Cost += getScalarizationOverhead(I, VF);
  5819. // If we have a predicated store, it may not be executed for each vector
  5820. // lane. Scale the cost by the probability of executing the predicated
  5821. // block.
  5822. if (isPredicatedInst(I)) {
  5823. Cost /= getReciprocalPredBlockProb();
  5824. if (useEmulatedMaskMemRefHack(I))
  5825. // Artificially setting to a high enough value to practically disable
  5826. // vectorization with such operations.
  5827. Cost = 3000000;
  5828. }
  5829. return Cost;
  5830. }
  5831. InstructionCost
  5832. LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
  5833. ElementCount VF) {
  5834. Type *ValTy = getMemInstValueType(I);
  5835. auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
  5836. Value *Ptr = getLoadStorePointerOperand(I);
  5837. unsigned AS = getLoadStoreAddressSpace(I);
  5838. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  5839. enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  5840. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  5841. "Stride should be 1 or -1 for consecutive memory access");
  5842. const Align Alignment = getLoadStoreAlignment(I);
  5843. InstructionCost Cost = 0;
  5844. if (Legal->isMaskRequired(I))
  5845. Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
  5846. CostKind);
  5847. else
  5848. Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
  5849. CostKind, I);
  5850. bool Reverse = ConsecutiveStride < 0;
  5851. if (Reverse)
  5852. Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
  5853. return Cost;
  5854. }
  5855. InstructionCost
  5856. LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
  5857. ElementCount VF) {
  5858. assert(Legal->isUniformMemOp(*I));
  5859. Type *ValTy = getMemInstValueType(I);
  5860. auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
  5861. const Align Alignment = getLoadStoreAlignment(I);
  5862. unsigned AS = getLoadStoreAddressSpace(I);
  5863. enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  5864. if (isa<LoadInst>(I)) {
  5865. return TTI.getAddressComputationCost(ValTy) +
  5866. TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
  5867. CostKind) +
  5868. TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
  5869. }
  5870. StoreInst *SI = cast<StoreInst>(I);
  5871. bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
  5872. return TTI.getAddressComputationCost(ValTy) +
  5873. TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
  5874. CostKind) +
  5875. (isLoopInvariantStoreValue
  5876. ? 0
  5877. : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
  5878. VF.getKnownMinValue() - 1));
  5879. }
  5880. InstructionCost
  5881. LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
  5882. ElementCount VF) {
  5883. Type *ValTy = getMemInstValueType(I);
  5884. auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
  5885. const Align Alignment = getLoadStoreAlignment(I);
  5886. const Value *Ptr = getLoadStorePointerOperand(I);
  5887. return TTI.getAddressComputationCost(VectorTy) +
  5888. TTI.getGatherScatterOpCost(
  5889. I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
  5890. TargetTransformInfo::TCK_RecipThroughput, I);
  5891. }
  5892. InstructionCost
  5893. LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
  5894. ElementCount VF) {
  5895. Type *ValTy = getMemInstValueType(I);
  5896. auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
  5897. unsigned AS = getLoadStoreAddressSpace(I);
  5898. auto Group = getInterleavedAccessGroup(I);
  5899. assert(Group && "Fail to get an interleaved access group.");
  5900. unsigned InterleaveFactor = Group->getFactor();
  5901. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  5902. auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
  5903. // Holds the indices of existing members in an interleaved load group.
  5904. // An interleaved store group doesn't need this as it doesn't allow gaps.
  5905. SmallVector<unsigned, 4> Indices;
  5906. if (isa<LoadInst>(I)) {
  5907. for (unsigned i = 0; i < InterleaveFactor; i++)
  5908. if (Group->getMember(i))
  5909. Indices.push_back(i);
  5910. }
  5911. // Calculate the cost of the whole interleaved group.
  5912. bool UseMaskForGaps =
  5913. Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
  5914. InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
  5915. I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
  5916. AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
  5917. if (Group->isReverse()) {
  5918. // TODO: Add support for reversed masked interleaved access.
  5919. assert(!Legal->isMaskRequired(I) &&
  5920. "Reverse masked interleaved access not supported.");
  5921. Cost += Group->getNumMembers() *
  5922. TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
  5923. }
  5924. return Cost;
  5925. }
  5926. InstructionCost LoopVectorizationCostModel::getReductionPatternCost(
  5927. Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
  5928. // Early exit for no inloop reductions
  5929. if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
  5930. return InstructionCost::getInvalid();
  5931. auto *VectorTy = cast<VectorType>(Ty);
  5932. // We are looking for a pattern of, and finding the minimal acceptable cost:
  5933. // reduce(mul(ext(A), ext(B))) or
  5934. // reduce(mul(A, B)) or
  5935. // reduce(ext(A)) or
  5936. // reduce(A).
  5937. // The basic idea is that we walk down the tree to do that, finding the root
  5938. // reduction instruction in InLoopReductionImmediateChains. From there we find
  5939. // the pattern of mul/ext and test the cost of the entire pattern vs the cost
  5940. // of the components. If the reduction cost is lower then we return it for the
  5941. // reduction instruction and 0 for the other instructions in the pattern. If
  5942. // it is not we return an invalid cost specifying the orignal cost method
  5943. // should be used.
  5944. Instruction *RetI = I;
  5945. if ((RetI->getOpcode() == Instruction::SExt ||
  5946. RetI->getOpcode() == Instruction::ZExt)) {
  5947. if (!RetI->hasOneUser())
  5948. return InstructionCost::getInvalid();
  5949. RetI = RetI->user_back();
  5950. }
  5951. if (RetI->getOpcode() == Instruction::Mul &&
  5952. RetI->user_back()->getOpcode() == Instruction::Add) {
  5953. if (!RetI->hasOneUser())
  5954. return InstructionCost::getInvalid();
  5955. RetI = RetI->user_back();
  5956. }
  5957. // Test if the found instruction is a reduction, and if not return an invalid
  5958. // cost specifying the parent to use the original cost modelling.
  5959. if (!InLoopReductionImmediateChains.count(RetI))
  5960. return InstructionCost::getInvalid();
  5961. // Find the reduction this chain is a part of and calculate the basic cost of
  5962. // the reduction on its own.
  5963. Instruction *LastChain = InLoopReductionImmediateChains[RetI];
  5964. Instruction *ReductionPhi = LastChain;
  5965. while (!isa<PHINode>(ReductionPhi))
  5966. ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
  5967. RecurrenceDescriptor RdxDesc =
  5968. Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
  5969. unsigned BaseCost = TTI.getArithmeticReductionCost(RdxDesc.getOpcode(),
  5970. VectorTy, false, CostKind);
  5971. // Get the operand that was not the reduction chain and match it to one of the
  5972. // patterns, returning the better cost if it is found.
  5973. Instruction *RedOp = RetI->getOperand(1) == LastChain
  5974. ? dyn_cast<Instruction>(RetI->getOperand(0))
  5975. : dyn_cast<Instruction>(RetI->getOperand(1));
  5976. VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
  5977. if (RedOp && (isa<SExtInst>(RedOp) || isa<ZExtInst>(RedOp)) &&
  5978. !TheLoop->isLoopInvariant(RedOp)) {
  5979. bool IsUnsigned = isa<ZExtInst>(RedOp);
  5980. auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
  5981. InstructionCost RedCost = TTI.getExtendedAddReductionCost(
  5982. /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
  5983. CostKind);
  5984. unsigned ExtCost =
  5985. TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
  5986. TTI::CastContextHint::None, CostKind, RedOp);
  5987. if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
  5988. return I == RetI ? *RedCost.getValue() : 0;
  5989. } else if (RedOp && RedOp->getOpcode() == Instruction::Mul) {
  5990. Instruction *Mul = RedOp;
  5991. Instruction *Op0 = dyn_cast<Instruction>(Mul->getOperand(0));
  5992. Instruction *Op1 = dyn_cast<Instruction>(Mul->getOperand(1));
  5993. if (Op0 && Op1 && (isa<SExtInst>(Op0) || isa<ZExtInst>(Op0)) &&
  5994. Op0->getOpcode() == Op1->getOpcode() &&
  5995. Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
  5996. !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
  5997. bool IsUnsigned = isa<ZExtInst>(Op0);
  5998. auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
  5999. // reduce(mul(ext, ext))
  6000. unsigned ExtCost =
  6001. TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
  6002. TTI::CastContextHint::None, CostKind, Op0);
  6003. unsigned MulCost =
  6004. TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
  6005. InstructionCost RedCost = TTI.getExtendedAddReductionCost(
  6006. /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
  6007. CostKind);
  6008. if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
  6009. return I == RetI ? *RedCost.getValue() : 0;
  6010. } else {
  6011. unsigned MulCost =
  6012. TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
  6013. InstructionCost RedCost = TTI.getExtendedAddReductionCost(
  6014. /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
  6015. CostKind);
  6016. if (RedCost.isValid() && RedCost < MulCost + BaseCost)
  6017. return I == RetI ? *RedCost.getValue() : 0;
  6018. }
  6019. }
  6020. return I == RetI ? BaseCost : InstructionCost::getInvalid();
  6021. }
  6022. InstructionCost
  6023. LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
  6024. ElementCount VF) {
  6025. // Calculate scalar cost only. Vectorization cost should be ready at this
  6026. // moment.
  6027. if (VF.isScalar()) {
  6028. Type *ValTy = getMemInstValueType(I);
  6029. const Align Alignment = getLoadStoreAlignment(I);
  6030. unsigned AS = getLoadStoreAddressSpace(I);
  6031. return TTI.getAddressComputationCost(ValTy) +
  6032. TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
  6033. TTI::TCK_RecipThroughput, I);
  6034. }
  6035. return getWideningCost(I, VF);
  6036. }
  6037. LoopVectorizationCostModel::VectorizationCostTy
  6038. LoopVectorizationCostModel::getInstructionCost(Instruction *I,
  6039. ElementCount VF) {
  6040. // If we know that this instruction will remain uniform, check the cost of
  6041. // the scalar version.
  6042. if (isUniformAfterVectorization(I, VF))
  6043. VF = ElementCount::getFixed(1);
  6044. if (VF.isVector() && isProfitableToScalarize(I, VF))
  6045. return VectorizationCostTy(InstsToScalarize[VF][I], false);
  6046. // Forced scalars do not have any scalarization overhead.
  6047. auto ForcedScalar = ForcedScalars.find(VF);
  6048. if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
  6049. auto InstSet = ForcedScalar->second;
  6050. if (InstSet.count(I))
  6051. return VectorizationCostTy(
  6052. (getInstructionCost(I, ElementCount::getFixed(1)).first *
  6053. VF.getKnownMinValue()),
  6054. false);
  6055. }
  6056. Type *VectorTy;
  6057. InstructionCost C = getInstructionCost(I, VF, VectorTy);
  6058. bool TypeNotScalarized =
  6059. VF.isVector() && VectorTy->isVectorTy() &&
  6060. TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
  6061. return VectorizationCostTy(C, TypeNotScalarized);
  6062. }
  6063. InstructionCost
  6064. LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
  6065. ElementCount VF) {
  6066. assert(!VF.isScalable() &&
  6067. "cannot compute scalarization overhead for scalable vectorization");
  6068. if (VF.isScalar())
  6069. return 0;
  6070. InstructionCost Cost = 0;
  6071. Type *RetTy = ToVectorTy(I->getType(), VF);
  6072. if (!RetTy->isVoidTy() &&
  6073. (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
  6074. Cost += TTI.getScalarizationOverhead(
  6075. cast<VectorType>(RetTy), APInt::getAllOnesValue(VF.getKnownMinValue()),
  6076. true, false);
  6077. // Some targets keep addresses scalar.
  6078. if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
  6079. return Cost;
  6080. // Some targets support efficient element stores.
  6081. if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
  6082. return Cost;
  6083. // Collect operands to consider.
  6084. CallInst *CI = dyn_cast<CallInst>(I);
  6085. Instruction::op_range Ops = CI ? CI->arg_operands() : I->operands();
  6086. // Skip operands that do not require extraction/scalarization and do not incur
  6087. // any overhead.
  6088. return Cost + TTI.getOperandsScalarizationOverhead(
  6089. filterExtractingOperands(Ops, VF), VF.getKnownMinValue());
  6090. }
  6091. void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
  6092. if (VF.isScalar())
  6093. return;
  6094. NumPredStores = 0;
  6095. for (BasicBlock *BB : TheLoop->blocks()) {
  6096. // For each instruction in the old loop.
  6097. for (Instruction &I : *BB) {
  6098. Value *Ptr = getLoadStorePointerOperand(&I);
  6099. if (!Ptr)
  6100. continue;
  6101. // TODO: We should generate better code and update the cost model for
  6102. // predicated uniform stores. Today they are treated as any other
  6103. // predicated store (see added test cases in
  6104. // invariant-store-vectorization.ll).
  6105. if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
  6106. NumPredStores++;
  6107. if (Legal->isUniformMemOp(I)) {
  6108. // TODO: Avoid replicating loads and stores instead of
  6109. // relying on instcombine to remove them.
  6110. // Load: Scalar load + broadcast
  6111. // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
  6112. InstructionCost Cost = getUniformMemOpCost(&I, VF);
  6113. setWideningDecision(&I, VF, CM_Scalarize, Cost);
  6114. continue;
  6115. }
  6116. // We assume that widening is the best solution when possible.
  6117. if (memoryInstructionCanBeWidened(&I, VF)) {
  6118. InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
  6119. int ConsecutiveStride =
  6120. Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
  6121. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  6122. "Expected consecutive stride.");
  6123. InstWidening Decision =
  6124. ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
  6125. setWideningDecision(&I, VF, Decision, Cost);
  6126. continue;
  6127. }
  6128. // Choose between Interleaving, Gather/Scatter or Scalarization.
  6129. InstructionCost InterleaveCost = std::numeric_limits<int>::max();
  6130. unsigned NumAccesses = 1;
  6131. if (isAccessInterleaved(&I)) {
  6132. auto Group = getInterleavedAccessGroup(&I);
  6133. assert(Group && "Fail to get an interleaved access group.");
  6134. // Make one decision for the whole group.
  6135. if (getWideningDecision(&I, VF) != CM_Unknown)
  6136. continue;
  6137. NumAccesses = Group->getNumMembers();
  6138. if (interleavedAccessCanBeWidened(&I, VF))
  6139. InterleaveCost = getInterleaveGroupCost(&I, VF);
  6140. }
  6141. InstructionCost GatherScatterCost =
  6142. isLegalGatherOrScatter(&I)
  6143. ? getGatherScatterCost(&I, VF) * NumAccesses
  6144. : std::numeric_limits<int>::max();
  6145. InstructionCost ScalarizationCost =
  6146. getMemInstScalarizationCost(&I, VF) * NumAccesses;
  6147. // Choose better solution for the current VF,
  6148. // write down this decision and use it during vectorization.
  6149. InstructionCost Cost;
  6150. InstWidening Decision;
  6151. if (InterleaveCost <= GatherScatterCost &&
  6152. InterleaveCost < ScalarizationCost) {
  6153. Decision = CM_Interleave;
  6154. Cost = InterleaveCost;
  6155. } else if (GatherScatterCost < ScalarizationCost) {
  6156. Decision = CM_GatherScatter;
  6157. Cost = GatherScatterCost;
  6158. } else {
  6159. Decision = CM_Scalarize;
  6160. Cost = ScalarizationCost;
  6161. }
  6162. // If the instructions belongs to an interleave group, the whole group
  6163. // receives the same decision. The whole group receives the cost, but
  6164. // the cost will actually be assigned to one instruction.
  6165. if (auto Group = getInterleavedAccessGroup(&I))
  6166. setWideningDecision(Group, VF, Decision, Cost);
  6167. else
  6168. setWideningDecision(&I, VF, Decision, Cost);
  6169. }
  6170. }
  6171. // Make sure that any load of address and any other address computation
  6172. // remains scalar unless there is gather/scatter support. This avoids
  6173. // inevitable extracts into address registers, and also has the benefit of
  6174. // activating LSR more, since that pass can't optimize vectorized
  6175. // addresses.
  6176. if (TTI.prefersVectorizedAddressing())
  6177. return;
  6178. // Start with all scalar pointer uses.
  6179. SmallPtrSet<Instruction *, 8> AddrDefs;
  6180. for (BasicBlock *BB : TheLoop->blocks())
  6181. for (Instruction &I : *BB) {
  6182. Instruction *PtrDef =
  6183. dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
  6184. if (PtrDef && TheLoop->contains(PtrDef) &&
  6185. getWideningDecision(&I, VF) != CM_GatherScatter)
  6186. AddrDefs.insert(PtrDef);
  6187. }
  6188. // Add all instructions used to generate the addresses.
  6189. SmallVector<Instruction *, 4> Worklist;
  6190. append_range(Worklist, AddrDefs);
  6191. while (!Worklist.empty()) {
  6192. Instruction *I = Worklist.pop_back_val();
  6193. for (auto &Op : I->operands())
  6194. if (auto *InstOp = dyn_cast<Instruction>(Op))
  6195. if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
  6196. AddrDefs.insert(InstOp).second)
  6197. Worklist.push_back(InstOp);
  6198. }
  6199. for (auto *I : AddrDefs) {
  6200. if (isa<LoadInst>(I)) {
  6201. // Setting the desired widening decision should ideally be handled in
  6202. // by cost functions, but since this involves the task of finding out
  6203. // if the loaded register is involved in an address computation, it is
  6204. // instead changed here when we know this is the case.
  6205. InstWidening Decision = getWideningDecision(I, VF);
  6206. if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
  6207. // Scalarize a widened load of address.
  6208. setWideningDecision(
  6209. I, VF, CM_Scalarize,
  6210. (VF.getKnownMinValue() *
  6211. getMemoryInstructionCost(I, ElementCount::getFixed(1))));
  6212. else if (auto Group = getInterleavedAccessGroup(I)) {
  6213. // Scalarize an interleave group of address loads.
  6214. for (unsigned I = 0; I < Group->getFactor(); ++I) {
  6215. if (Instruction *Member = Group->getMember(I))
  6216. setWideningDecision(
  6217. Member, VF, CM_Scalarize,
  6218. (VF.getKnownMinValue() *
  6219. getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
  6220. }
  6221. }
  6222. } else
  6223. // Make sure I gets scalarized and a cost estimate without
  6224. // scalarization overhead.
  6225. ForcedScalars[VF].insert(I);
  6226. }
  6227. }
  6228. InstructionCost
  6229. LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
  6230. Type *&VectorTy) {
  6231. Type *RetTy = I->getType();
  6232. if (canTruncateToMinimalBitwidth(I, VF))
  6233. RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
  6234. VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
  6235. auto SE = PSE.getSE();
  6236. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  6237. // TODO: We need to estimate the cost of intrinsic calls.
  6238. switch (I->getOpcode()) {
  6239. case Instruction::GetElementPtr:
  6240. // We mark this instruction as zero-cost because the cost of GEPs in
  6241. // vectorized code depends on whether the corresponding memory instruction
  6242. // is scalarized or not. Therefore, we handle GEPs with the memory
  6243. // instruction cost.
  6244. return 0;
  6245. case Instruction::Br: {
  6246. // In cases of scalarized and predicated instructions, there will be VF
  6247. // predicated blocks in the vectorized loop. Each branch around these
  6248. // blocks requires also an extract of its vector compare i1 element.
  6249. bool ScalarPredicatedBB = false;
  6250. BranchInst *BI = cast<BranchInst>(I);
  6251. if (VF.isVector() && BI->isConditional() &&
  6252. (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
  6253. PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
  6254. ScalarPredicatedBB = true;
  6255. if (ScalarPredicatedBB) {
  6256. // Return cost for branches around scalarized and predicated blocks.
  6257. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  6258. auto *Vec_i1Ty =
  6259. VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
  6260. return (TTI.getScalarizationOverhead(
  6261. Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
  6262. false, true) +
  6263. (TTI.getCFInstrCost(Instruction::Br, CostKind) *
  6264. VF.getKnownMinValue()));
  6265. } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
  6266. // The back-edge branch will remain, as will all scalar branches.
  6267. return TTI.getCFInstrCost(Instruction::Br, CostKind);
  6268. else
  6269. // This branch will be eliminated by if-conversion.
  6270. return 0;
  6271. // Note: We currently assume zero cost for an unconditional branch inside
  6272. // a predicated block since it will become a fall-through, although we
  6273. // may decide in the future to call TTI for all branches.
  6274. }
  6275. case Instruction::PHI: {
  6276. auto *Phi = cast<PHINode>(I);
  6277. // First-order recurrences are replaced by vector shuffles inside the loop.
  6278. // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
  6279. if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
  6280. return TTI.getShuffleCost(
  6281. TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
  6282. VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
  6283. // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
  6284. // converted into select instructions. We require N - 1 selects per phi
  6285. // node, where N is the number of incoming values.
  6286. if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
  6287. return (Phi->getNumIncomingValues() - 1) *
  6288. TTI.getCmpSelInstrCost(
  6289. Instruction::Select, ToVectorTy(Phi->getType(), VF),
  6290. ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
  6291. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  6292. return TTI.getCFInstrCost(Instruction::PHI, CostKind);
  6293. }
  6294. case Instruction::UDiv:
  6295. case Instruction::SDiv:
  6296. case Instruction::URem:
  6297. case Instruction::SRem:
  6298. // If we have a predicated instruction, it may not be executed for each
  6299. // vector lane. Get the scalarization cost and scale this amount by the
  6300. // probability of executing the predicated block. If the instruction is not
  6301. // predicated, we fall through to the next case.
  6302. if (VF.isVector() && isScalarWithPredication(I)) {
  6303. InstructionCost Cost = 0;
  6304. // These instructions have a non-void type, so account for the phi nodes
  6305. // that we will create. This cost is likely to be zero. The phi node
  6306. // cost, if any, should be scaled by the block probability because it
  6307. // models a copy at the end of each predicated block.
  6308. Cost += VF.getKnownMinValue() *
  6309. TTI.getCFInstrCost(Instruction::PHI, CostKind);
  6310. // The cost of the non-predicated instruction.
  6311. Cost += VF.getKnownMinValue() *
  6312. TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
  6313. // The cost of insertelement and extractelement instructions needed for
  6314. // scalarization.
  6315. Cost += getScalarizationOverhead(I, VF);
  6316. // Scale the cost by the probability of executing the predicated blocks.
  6317. // This assumes the predicated block for each vector lane is equally
  6318. // likely.
  6319. return Cost / getReciprocalPredBlockProb();
  6320. }
  6321. LLVM_FALLTHROUGH;
  6322. case Instruction::Add:
  6323. case Instruction::FAdd:
  6324. case Instruction::Sub:
  6325. case Instruction::FSub:
  6326. case Instruction::Mul:
  6327. case Instruction::FMul:
  6328. case Instruction::FDiv:
  6329. case Instruction::FRem:
  6330. case Instruction::Shl:
  6331. case Instruction::LShr:
  6332. case Instruction::AShr:
  6333. case Instruction::And:
  6334. case Instruction::Or:
  6335. case Instruction::Xor: {
  6336. // Since we will replace the stride by 1 the multiplication should go away.
  6337. if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
  6338. return 0;
  6339. // Detect reduction patterns
  6340. InstructionCost RedCost;
  6341. if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
  6342. .isValid())
  6343. return RedCost;
  6344. // Certain instructions can be cheaper to vectorize if they have a constant
  6345. // second vector operand. One example of this are shifts on x86.
  6346. Value *Op2 = I->getOperand(1);
  6347. TargetTransformInfo::OperandValueProperties Op2VP;
  6348. TargetTransformInfo::OperandValueKind Op2VK =
  6349. TTI.getOperandInfo(Op2, Op2VP);
  6350. if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
  6351. Op2VK = TargetTransformInfo::OK_UniformValue;
  6352. SmallVector<const Value *, 4> Operands(I->operand_values());
  6353. unsigned N = isScalarAfterVectorization(I, VF) ? VF.getKnownMinValue() : 1;
  6354. return N * TTI.getArithmeticInstrCost(
  6355. I->getOpcode(), VectorTy, CostKind,
  6356. TargetTransformInfo::OK_AnyValue,
  6357. Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
  6358. }
  6359. case Instruction::FNeg: {
  6360. assert(!VF.isScalable() && "VF is assumed to be non scalable.");
  6361. unsigned N = isScalarAfterVectorization(I, VF) ? VF.getKnownMinValue() : 1;
  6362. return N * TTI.getArithmeticInstrCost(
  6363. I->getOpcode(), VectorTy, CostKind,
  6364. TargetTransformInfo::OK_AnyValue,
  6365. TargetTransformInfo::OK_AnyValue,
  6366. TargetTransformInfo::OP_None, TargetTransformInfo::OP_None,
  6367. I->getOperand(0), I);
  6368. }
  6369. case Instruction::Select: {
  6370. SelectInst *SI = cast<SelectInst>(I);
  6371. const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
  6372. bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
  6373. Type *CondTy = SI->getCondition()->getType();
  6374. if (!ScalarCond)
  6375. CondTy = VectorType::get(CondTy, VF);
  6376. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
  6377. CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
  6378. }
  6379. case Instruction::ICmp:
  6380. case Instruction::FCmp: {
  6381. Type *ValTy = I->getOperand(0)->getType();
  6382. Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
  6383. if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
  6384. ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
  6385. VectorTy = ToVectorTy(ValTy, VF);
  6386. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
  6387. CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
  6388. }
  6389. case Instruction::Store:
  6390. case Instruction::Load: {
  6391. ElementCount Width = VF;
  6392. if (Width.isVector()) {
  6393. InstWidening Decision = getWideningDecision(I, Width);
  6394. assert(Decision != CM_Unknown &&
  6395. "CM decision should be taken at this point");
  6396. if (Decision == CM_Scalarize)
  6397. Width = ElementCount::getFixed(1);
  6398. }
  6399. VectorTy = ToVectorTy(getMemInstValueType(I), Width);
  6400. return getMemoryInstructionCost(I, VF);
  6401. }
  6402. case Instruction::ZExt:
  6403. case Instruction::SExt:
  6404. case Instruction::FPToUI:
  6405. case Instruction::FPToSI:
  6406. case Instruction::FPExt:
  6407. case Instruction::PtrToInt:
  6408. case Instruction::IntToPtr:
  6409. case Instruction::SIToFP:
  6410. case Instruction::UIToFP:
  6411. case Instruction::Trunc:
  6412. case Instruction::FPTrunc:
  6413. case Instruction::BitCast: {
  6414. // Computes the CastContextHint from a Load/Store instruction.
  6415. auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
  6416. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  6417. "Expected a load or a store!");
  6418. if (VF.isScalar() || !TheLoop->contains(I))
  6419. return TTI::CastContextHint::Normal;
  6420. switch (getWideningDecision(I, VF)) {
  6421. case LoopVectorizationCostModel::CM_GatherScatter:
  6422. return TTI::CastContextHint::GatherScatter;
  6423. case LoopVectorizationCostModel::CM_Interleave:
  6424. return TTI::CastContextHint::Interleave;
  6425. case LoopVectorizationCostModel::CM_Scalarize:
  6426. case LoopVectorizationCostModel::CM_Widen:
  6427. return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
  6428. : TTI::CastContextHint::Normal;
  6429. case LoopVectorizationCostModel::CM_Widen_Reverse:
  6430. return TTI::CastContextHint::Reversed;
  6431. case LoopVectorizationCostModel::CM_Unknown:
  6432. llvm_unreachable("Instr did not go through cost modelling?");
  6433. }
  6434. llvm_unreachable("Unhandled case!");
  6435. };
  6436. unsigned Opcode = I->getOpcode();
  6437. TTI::CastContextHint CCH = TTI::CastContextHint::None;
  6438. // For Trunc, the context is the only user, which must be a StoreInst.
  6439. if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
  6440. if (I->hasOneUse())
  6441. if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
  6442. CCH = ComputeCCH(Store);
  6443. }
  6444. // For Z/Sext, the context is the operand, which must be a LoadInst.
  6445. else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
  6446. Opcode == Instruction::FPExt) {
  6447. if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
  6448. CCH = ComputeCCH(Load);
  6449. }
  6450. // We optimize the truncation of induction variables having constant
  6451. // integer steps. The cost of these truncations is the same as the scalar
  6452. // operation.
  6453. if (isOptimizableIVTruncate(I, VF)) {
  6454. auto *Trunc = cast<TruncInst>(I);
  6455. return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
  6456. Trunc->getSrcTy(), CCH, CostKind, Trunc);
  6457. }
  6458. // Detect reduction patterns
  6459. InstructionCost RedCost;
  6460. if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
  6461. .isValid())
  6462. return RedCost;
  6463. Type *SrcScalarTy = I->getOperand(0)->getType();
  6464. Type *SrcVecTy =
  6465. VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
  6466. if (canTruncateToMinimalBitwidth(I, VF)) {
  6467. // This cast is going to be shrunk. This may remove the cast or it might
  6468. // turn it into slightly different cast. For example, if MinBW == 16,
  6469. // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
  6470. //
  6471. // Calculate the modified src and dest types.
  6472. Type *MinVecTy = VectorTy;
  6473. if (Opcode == Instruction::Trunc) {
  6474. SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
  6475. VectorTy =
  6476. largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  6477. } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
  6478. SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
  6479. VectorTy =
  6480. smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  6481. }
  6482. }
  6483. assert(!VF.isScalable() && "VF is assumed to be non scalable");
  6484. unsigned N = isScalarAfterVectorization(I, VF) ? VF.getKnownMinValue() : 1;
  6485. return N *
  6486. TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
  6487. }
  6488. case Instruction::Call: {
  6489. bool NeedToScalarize;
  6490. CallInst *CI = cast<CallInst>(I);
  6491. InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
  6492. if (getVectorIntrinsicIDForCall(CI, TLI)) {
  6493. InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
  6494. return std::min(CallCost, IntrinsicCost);
  6495. }
  6496. return CallCost;
  6497. }
  6498. case Instruction::ExtractValue:
  6499. return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
  6500. default:
  6501. // The cost of executing VF copies of the scalar instruction. This opcode
  6502. // is unknown. Assume that it is the same as 'mul'.
  6503. return VF.getKnownMinValue() * TTI.getArithmeticInstrCost(
  6504. Instruction::Mul, VectorTy, CostKind) +
  6505. getScalarizationOverhead(I, VF);
  6506. } // end of switch.
  6507. }
  6508. char LoopVectorize::ID = 0;
  6509. static const char lv_name[] = "Loop Vectorization";
  6510. INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
  6511. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  6512. INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
  6513. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  6514. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  6515. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  6516. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  6517. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  6518. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  6519. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  6520. INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
  6521. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  6522. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  6523. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  6524. INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
  6525. INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
  6526. namespace llvm {
  6527. Pass *createLoopVectorizePass() { return new LoopVectorize(); }
  6528. Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
  6529. bool VectorizeOnlyWhenForced) {
  6530. return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
  6531. }
  6532. } // end namespace llvm
  6533. bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
  6534. // Check if the pointer operand of a load or store instruction is
  6535. // consecutive.
  6536. if (auto *Ptr = getLoadStorePointerOperand(Inst))
  6537. return Legal->isConsecutivePtr(Ptr);
  6538. return false;
  6539. }
  6540. void LoopVectorizationCostModel::collectValuesToIgnore() {
  6541. // Ignore ephemeral values.
  6542. CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
  6543. // Ignore type-promoting instructions we identified during reduction
  6544. // detection.
  6545. for (auto &Reduction : Legal->getReductionVars()) {
  6546. RecurrenceDescriptor &RedDes = Reduction.second;
  6547. const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
  6548. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  6549. }
  6550. // Ignore type-casting instructions we identified during induction
  6551. // detection.
  6552. for (auto &Induction : Legal->getInductionVars()) {
  6553. InductionDescriptor &IndDes = Induction.second;
  6554. const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
  6555. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  6556. }
  6557. }
  6558. void LoopVectorizationCostModel::collectInLoopReductions() {
  6559. for (auto &Reduction : Legal->getReductionVars()) {
  6560. PHINode *Phi = Reduction.first;
  6561. RecurrenceDescriptor &RdxDesc = Reduction.second;
  6562. // We don't collect reductions that are type promoted (yet).
  6563. if (RdxDesc.getRecurrenceType() != Phi->getType())
  6564. continue;
  6565. // If the target would prefer this reduction to happen "in-loop", then we
  6566. // want to record it as such.
  6567. unsigned Opcode = RdxDesc.getOpcode();
  6568. if (!PreferInLoopReductions &&
  6569. !TTI.preferInLoopReduction(Opcode, Phi->getType(),
  6570. TargetTransformInfo::ReductionFlags()))
  6571. continue;
  6572. // Check that we can correctly put the reductions into the loop, by
  6573. // finding the chain of operations that leads from the phi to the loop
  6574. // exit value.
  6575. SmallVector<Instruction *, 4> ReductionOperations =
  6576. RdxDesc.getReductionOpChain(Phi, TheLoop);
  6577. bool InLoop = !ReductionOperations.empty();
  6578. if (InLoop) {
  6579. InLoopReductionChains[Phi] = ReductionOperations;
  6580. // Add the elements to InLoopReductionImmediateChains for cost modelling.
  6581. Instruction *LastChain = Phi;
  6582. for (auto *I : ReductionOperations) {
  6583. InLoopReductionImmediateChains[I] = LastChain;
  6584. LastChain = I;
  6585. }
  6586. }
  6587. LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
  6588. << " reduction for phi: " << *Phi << "\n");
  6589. }
  6590. }
  6591. // TODO: we could return a pair of values that specify the max VF and
  6592. // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
  6593. // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
  6594. // doesn't have a cost model that can choose which plan to execute if
  6595. // more than one is generated.
  6596. static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
  6597. LoopVectorizationCostModel &CM) {
  6598. unsigned WidestType;
  6599. std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
  6600. return WidestVectorRegBits / WidestType;
  6601. }
  6602. VectorizationFactor
  6603. LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
  6604. assert(!UserVF.isScalable() && "scalable vectors not yet supported");
  6605. ElementCount VF = UserVF;
  6606. // Outer loop handling: They may require CFG and instruction level
  6607. // transformations before even evaluating whether vectorization is profitable.
  6608. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  6609. // the vectorization pipeline.
  6610. if (!OrigLoop->isInnermost()) {
  6611. // If the user doesn't provide a vectorization factor, determine a
  6612. // reasonable one.
  6613. if (UserVF.isZero()) {
  6614. VF = ElementCount::getFixed(
  6615. determineVPlanVF(TTI->getRegisterBitWidth(true /* Vector*/), CM));
  6616. LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
  6617. // Make sure we have a VF > 1 for stress testing.
  6618. if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
  6619. LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
  6620. << "overriding computed VF.\n");
  6621. VF = ElementCount::getFixed(4);
  6622. }
  6623. }
  6624. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  6625. assert(isPowerOf2_32(VF.getKnownMinValue()) &&
  6626. "VF needs to be a power of two");
  6627. LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
  6628. << "VF " << VF << " to build VPlans.\n");
  6629. buildVPlans(VF, VF);
  6630. // For VPlan build stress testing, we bail out after VPlan construction.
  6631. if (VPlanBuildStressTest)
  6632. return VectorizationFactor::Disabled();
  6633. return {VF, 0 /*Cost*/};
  6634. }
  6635. LLVM_DEBUG(
  6636. dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
  6637. "VPlan-native path.\n");
  6638. return VectorizationFactor::Disabled();
  6639. }
  6640. Optional<VectorizationFactor>
  6641. LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
  6642. assert(OrigLoop->isInnermost() && "Inner loop expected.");
  6643. Optional<ElementCount> MaybeMaxVF = CM.computeMaxVF(UserVF, UserIC);
  6644. if (!MaybeMaxVF) // Cases that should not to be vectorized nor interleaved.
  6645. return None;
  6646. // Invalidate interleave groups if all blocks of loop will be predicated.
  6647. if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
  6648. !useMaskedInterleavedAccesses(*TTI)) {
  6649. LLVM_DEBUG(
  6650. dbgs()
  6651. << "LV: Invalidate all interleaved groups due to fold-tail by masking "
  6652. "which requires masked-interleaved support.\n");
  6653. if (CM.InterleaveInfo.invalidateGroups())
  6654. // Invalidating interleave groups also requires invalidating all decisions
  6655. // based on them, which includes widening decisions and uniform and scalar
  6656. // values.
  6657. CM.invalidateCostModelingDecisions();
  6658. }
  6659. ElementCount MaxVF = MaybeMaxVF.getValue();
  6660. assert(MaxVF.isNonZero() && "MaxVF is zero.");
  6661. bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxVF);
  6662. if (!UserVF.isZero() &&
  6663. (UserVFIsLegal || (UserVF.isScalable() && MaxVF.isScalable()))) {
  6664. // FIXME: MaxVF is temporarily used inplace of UserVF for illegal scalable
  6665. // VFs here, this should be reverted to only use legal UserVFs once the
  6666. // loop below supports scalable VFs.
  6667. ElementCount VF = UserVFIsLegal ? UserVF : MaxVF;
  6668. LLVM_DEBUG(dbgs() << "LV: Using " << (UserVFIsLegal ? "user" : "max")
  6669. << " VF " << VF << ".\n");
  6670. assert(isPowerOf2_32(VF.getKnownMinValue()) &&
  6671. "VF needs to be a power of two");
  6672. // Collect the instructions (and their associated costs) that will be more
  6673. // profitable to scalarize.
  6674. CM.selectUserVectorizationFactor(VF);
  6675. CM.collectInLoopReductions();
  6676. buildVPlansWithVPRecipes(VF, VF);
  6677. LLVM_DEBUG(printPlans(dbgs()));
  6678. return {{VF, 0}};
  6679. }
  6680. assert(!MaxVF.isScalable() &&
  6681. "Scalable vectors not yet supported beyond this point");
  6682. for (ElementCount VF = ElementCount::getFixed(1);
  6683. ElementCount::isKnownLE(VF, MaxVF); VF *= 2) {
  6684. // Collect Uniform and Scalar instructions after vectorization with VF.
  6685. CM.collectUniformsAndScalars(VF);
  6686. // Collect the instructions (and their associated costs) that will be more
  6687. // profitable to scalarize.
  6688. if (VF.isVector())
  6689. CM.collectInstsToScalarize(VF);
  6690. }
  6691. CM.collectInLoopReductions();
  6692. buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxVF);
  6693. LLVM_DEBUG(printPlans(dbgs()));
  6694. if (MaxVF.isScalar())
  6695. return VectorizationFactor::Disabled();
  6696. // Select the optimal vectorization factor.
  6697. return CM.selectVectorizationFactor(MaxVF);
  6698. }
  6699. void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
  6700. LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
  6701. << '\n');
  6702. BestVF = VF;
  6703. BestUF = UF;
  6704. erase_if(VPlans, [VF](const VPlanPtr &Plan) {
  6705. return !Plan->hasVF(VF);
  6706. });
  6707. assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
  6708. }
  6709. void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
  6710. DominatorTree *DT) {
  6711. // Perform the actual loop transformation.
  6712. // 1. Create a new empty loop. Unlink the old loop and connect the new one.
  6713. VPCallbackILV CallbackILV(ILV);
  6714. assert(BestVF.hasValue() && "Vectorization Factor is missing");
  6715. VPTransformState State{*BestVF,
  6716. BestUF,
  6717. OrigLoop,
  6718. LI,
  6719. DT,
  6720. ILV.Builder,
  6721. ILV.VectorLoopValueMap,
  6722. &ILV,
  6723. CallbackILV};
  6724. State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
  6725. State.TripCount = ILV.getOrCreateTripCount(nullptr);
  6726. State.CanonicalIV = ILV.Induction;
  6727. ILV.printDebugTracesAtStart();
  6728. //===------------------------------------------------===//
  6729. //
  6730. // Notice: any optimization or new instruction that go
  6731. // into the code below should also be implemented in
  6732. // the cost-model.
  6733. //
  6734. //===------------------------------------------------===//
  6735. // 2. Copy and widen instructions from the old loop into the new loop.
  6736. assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
  6737. VPlans.front()->execute(&State);
  6738. // 3. Fix the vectorized code: take care of header phi's, live-outs,
  6739. // predication, updating analyses.
  6740. ILV.fixVectorizedLoop();
  6741. ILV.printDebugTracesAtEnd();
  6742. }
  6743. void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
  6744. SmallPtrSetImpl<Instruction *> &DeadInstructions) {
  6745. // We create new control-flow for the vectorized loop, so the original exit
  6746. // conditions will be dead after vectorization if it's only used by the
  6747. // terminator
  6748. SmallVector<BasicBlock*> ExitingBlocks;
  6749. OrigLoop->getExitingBlocks(ExitingBlocks);
  6750. for (auto *BB : ExitingBlocks) {
  6751. auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
  6752. if (!Cmp || !Cmp->hasOneUse())
  6753. continue;
  6754. // TODO: we should introduce a getUniqueExitingBlocks on Loop
  6755. if (!DeadInstructions.insert(Cmp).second)
  6756. continue;
  6757. // The operands of the icmp is often a dead trunc, used by IndUpdate.
  6758. // TODO: can recurse through operands in general
  6759. for (Value *Op : Cmp->operands()) {
  6760. if (isa<TruncInst>(Op) && Op->hasOneUse())
  6761. DeadInstructions.insert(cast<Instruction>(Op));
  6762. }
  6763. }
  6764. // We create new "steps" for induction variable updates to which the original
  6765. // induction variables map. An original update instruction will be dead if
  6766. // all its users except the induction variable are dead.
  6767. auto *Latch = OrigLoop->getLoopLatch();
  6768. for (auto &Induction : Legal->getInductionVars()) {
  6769. PHINode *Ind = Induction.first;
  6770. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  6771. // If the tail is to be folded by masking, the primary induction variable,
  6772. // if exists, isn't dead: it will be used for masking. Don't kill it.
  6773. if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
  6774. continue;
  6775. if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  6776. return U == Ind || DeadInstructions.count(cast<Instruction>(U));
  6777. }))
  6778. DeadInstructions.insert(IndUpdate);
  6779. // We record as "Dead" also the type-casting instructions we had identified
  6780. // during induction analysis. We don't need any handling for them in the
  6781. // vectorized loop because we have proven that, under a proper runtime
  6782. // test guarding the vectorized loop, the value of the phi, and the casted
  6783. // value of the phi, are the same. The last instruction in this casting chain
  6784. // will get its scalar/vector/widened def from the scalar/vector/widened def
  6785. // of the respective phi node. Any other casts in the induction def-use chain
  6786. // have no other uses outside the phi update chain, and will be ignored.
  6787. InductionDescriptor &IndDes = Induction.second;
  6788. const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
  6789. DeadInstructions.insert(Casts.begin(), Casts.end());
  6790. }
  6791. }
  6792. Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
  6793. Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
  6794. Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
  6795. Instruction::BinaryOps BinOp) {
  6796. // When unrolling and the VF is 1, we only need to add a simple scalar.
  6797. Type *Ty = Val->getType();
  6798. assert(!Ty->isVectorTy() && "Val must be a scalar");
  6799. if (Ty->isFloatingPointTy()) {
  6800. Constant *C = ConstantFP::get(Ty, (double)StartIdx);
  6801. // Floating point operations had to be 'fast' to enable the unrolling.
  6802. Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
  6803. return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
  6804. }
  6805. Constant *C = ConstantInt::get(Ty, StartIdx);
  6806. return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
  6807. }
  6808. static void AddRuntimeUnrollDisableMetaData(Loop *L) {
  6809. SmallVector<Metadata *, 4> MDs;
  6810. // Reserve first location for self reference to the LoopID metadata node.
  6811. MDs.push_back(nullptr);
  6812. bool IsUnrollMetadata = false;
  6813. MDNode *LoopID = L->getLoopID();
  6814. if (LoopID) {
  6815. // First find existing loop unrolling disable metadata.
  6816. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  6817. auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  6818. if (MD) {
  6819. const auto *S = dyn_cast<MDString>(MD->getOperand(0));
  6820. IsUnrollMetadata =
  6821. S && S->getString().startswith("llvm.loop.unroll.disable");
  6822. }
  6823. MDs.push_back(LoopID->getOperand(i));
  6824. }
  6825. }
  6826. if (!IsUnrollMetadata) {
  6827. // Add runtime unroll disable metadata.
  6828. LLVMContext &Context = L->getHeader()->getContext();
  6829. SmallVector<Metadata *, 1> DisableOperands;
  6830. DisableOperands.push_back(
  6831. MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
  6832. MDNode *DisableNode = MDNode::get(Context, DisableOperands);
  6833. MDs.push_back(DisableNode);
  6834. MDNode *NewLoopID = MDNode::get(Context, MDs);
  6835. // Set operand 0 to refer to the loop id itself.
  6836. NewLoopID->replaceOperandWith(0, NewLoopID);
  6837. L->setLoopID(NewLoopID);
  6838. }
  6839. }
  6840. //===--------------------------------------------------------------------===//
  6841. // EpilogueVectorizerMainLoop
  6842. //===--------------------------------------------------------------------===//
  6843. /// This function is partially responsible for generating the control flow
  6844. /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
  6845. BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
  6846. MDNode *OrigLoopID = OrigLoop->getLoopID();
  6847. Loop *Lp = createVectorLoopSkeleton("");
  6848. // Generate the code to check the minimum iteration count of the vector
  6849. // epilogue (see below).
  6850. EPI.EpilogueIterationCountCheck =
  6851. emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
  6852. EPI.EpilogueIterationCountCheck->setName("iter.check");
  6853. // Generate the code to check any assumptions that we've made for SCEV
  6854. // expressions.
  6855. BasicBlock *SavedPreHeader = LoopVectorPreHeader;
  6856. emitSCEVChecks(Lp, LoopScalarPreHeader);
  6857. // If a safety check was generated save it.
  6858. if (SavedPreHeader != LoopVectorPreHeader)
  6859. EPI.SCEVSafetyCheck = SavedPreHeader;
  6860. // Generate the code that checks at runtime if arrays overlap. We put the
  6861. // checks into a separate block to make the more common case of few elements
  6862. // faster.
  6863. SavedPreHeader = LoopVectorPreHeader;
  6864. emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
  6865. // If a safety check was generated save/overwite it.
  6866. if (SavedPreHeader != LoopVectorPreHeader)
  6867. EPI.MemSafetyCheck = SavedPreHeader;
  6868. // Generate the iteration count check for the main loop, *after* the check
  6869. // for the epilogue loop, so that the path-length is shorter for the case
  6870. // that goes directly through the vector epilogue. The longer-path length for
  6871. // the main loop is compensated for, by the gain from vectorizing the larger
  6872. // trip count. Note: the branch will get updated later on when we vectorize
  6873. // the epilogue.
  6874. EPI.MainLoopIterationCountCheck =
  6875. emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
  6876. // Generate the induction variable.
  6877. OldInduction = Legal->getPrimaryInduction();
  6878. Type *IdxTy = Legal->getWidestInductionType();
  6879. Value *StartIdx = ConstantInt::get(IdxTy, 0);
  6880. Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
  6881. Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
  6882. EPI.VectorTripCount = CountRoundDown;
  6883. Induction =
  6884. createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
  6885. getDebugLocFromInstOrOperands(OldInduction));
  6886. // Skip induction resume value creation here because they will be created in
  6887. // the second pass. If we created them here, they wouldn't be used anyway,
  6888. // because the vplan in the second pass still contains the inductions from the
  6889. // original loop.
  6890. return completeLoopSkeleton(Lp, OrigLoopID);
  6891. }
  6892. void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
  6893. LLVM_DEBUG({
  6894. dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
  6895. << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
  6896. << ", Main Loop UF:" << EPI.MainLoopUF
  6897. << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
  6898. << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
  6899. });
  6900. }
  6901. void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
  6902. DEBUG_WITH_TYPE(VerboseDebug, {
  6903. dbgs() << "intermediate fn:\n" << *Induction->getFunction() << "\n";
  6904. });
  6905. }
  6906. BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
  6907. Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
  6908. assert(L && "Expected valid Loop.");
  6909. assert(Bypass && "Expected valid bypass basic block.");
  6910. unsigned VFactor =
  6911. ForEpilogue ? EPI.EpilogueVF.getKnownMinValue() : VF.getKnownMinValue();
  6912. unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
  6913. Value *Count = getOrCreateTripCount(L);
  6914. // Reuse existing vector loop preheader for TC checks.
  6915. // Note that new preheader block is generated for vector loop.
  6916. BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
  6917. IRBuilder<> Builder(TCCheckBlock->getTerminator());
  6918. // Generate code to check if the loop's trip count is less than VF * UF of the
  6919. // main vector loop.
  6920. auto P =
  6921. Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
  6922. Value *CheckMinIters = Builder.CreateICmp(
  6923. P, Count, ConstantInt::get(Count->getType(), VFactor * UFactor),
  6924. "min.iters.check");
  6925. if (!ForEpilogue)
  6926. TCCheckBlock->setName("vector.main.loop.iter.check");
  6927. // Create new preheader for vector loop.
  6928. LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
  6929. DT, LI, nullptr, "vector.ph");
  6930. if (ForEpilogue) {
  6931. assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
  6932. DT->getNode(Bypass)->getIDom()) &&
  6933. "TC check is expected to dominate Bypass");
  6934. // Update dominator for Bypass & LoopExit.
  6935. DT->changeImmediateDominator(Bypass, TCCheckBlock);
  6936. DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
  6937. LoopBypassBlocks.push_back(TCCheckBlock);
  6938. // Save the trip count so we don't have to regenerate it in the
  6939. // vec.epilog.iter.check. This is safe to do because the trip count
  6940. // generated here dominates the vector epilog iter check.
  6941. EPI.TripCount = Count;
  6942. }
  6943. ReplaceInstWithInst(
  6944. TCCheckBlock->getTerminator(),
  6945. BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
  6946. return TCCheckBlock;
  6947. }
  6948. //===--------------------------------------------------------------------===//
  6949. // EpilogueVectorizerEpilogueLoop
  6950. //===--------------------------------------------------------------------===//
  6951. /// This function is partially responsible for generating the control flow
  6952. /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
  6953. BasicBlock *
  6954. EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
  6955. MDNode *OrigLoopID = OrigLoop->getLoopID();
  6956. Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
  6957. // Now, compare the remaining count and if there aren't enough iterations to
  6958. // execute the vectorized epilogue skip to the scalar part.
  6959. BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
  6960. VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
  6961. LoopVectorPreHeader =
  6962. SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
  6963. LI, nullptr, "vec.epilog.ph");
  6964. emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
  6965. VecEpilogueIterationCountCheck);
  6966. // Adjust the control flow taking the state info from the main loop
  6967. // vectorization into account.
  6968. assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
  6969. "expected this to be saved from the previous pass.");
  6970. EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
  6971. VecEpilogueIterationCountCheck, LoopVectorPreHeader);
  6972. DT->changeImmediateDominator(LoopVectorPreHeader,
  6973. EPI.MainLoopIterationCountCheck);
  6974. EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
  6975. VecEpilogueIterationCountCheck, LoopScalarPreHeader);
  6976. if (EPI.SCEVSafetyCheck)
  6977. EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
  6978. VecEpilogueIterationCountCheck, LoopScalarPreHeader);
  6979. if (EPI.MemSafetyCheck)
  6980. EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
  6981. VecEpilogueIterationCountCheck, LoopScalarPreHeader);
  6982. DT->changeImmediateDominator(
  6983. VecEpilogueIterationCountCheck,
  6984. VecEpilogueIterationCountCheck->getSinglePredecessor());
  6985. DT->changeImmediateDominator(LoopScalarPreHeader,
  6986. EPI.EpilogueIterationCountCheck);
  6987. DT->changeImmediateDominator(LoopExitBlock, EPI.EpilogueIterationCountCheck);
  6988. // Keep track of bypass blocks, as they feed start values to the induction
  6989. // phis in the scalar loop preheader.
  6990. if (EPI.SCEVSafetyCheck)
  6991. LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
  6992. if (EPI.MemSafetyCheck)
  6993. LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
  6994. LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
  6995. // Generate a resume induction for the vector epilogue and put it in the
  6996. // vector epilogue preheader
  6997. Type *IdxTy = Legal->getWidestInductionType();
  6998. PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
  6999. LoopVectorPreHeader->getFirstNonPHI());
  7000. EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
  7001. EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
  7002. EPI.MainLoopIterationCountCheck);
  7003. // Generate the induction variable.
  7004. OldInduction = Legal->getPrimaryInduction();
  7005. Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
  7006. Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
  7007. Value *StartIdx = EPResumeVal;
  7008. Induction =
  7009. createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
  7010. getDebugLocFromInstOrOperands(OldInduction));
  7011. // Generate induction resume values. These variables save the new starting
  7012. // indexes for the scalar loop. They are used to test if there are any tail
  7013. // iterations left once the vector loop has completed.
  7014. // Note that when the vectorized epilogue is skipped due to iteration count
  7015. // check, then the resume value for the induction variable comes from
  7016. // the trip count of the main vector loop, hence passing the AdditionalBypass
  7017. // argument.
  7018. createInductionResumeValues(Lp, CountRoundDown,
  7019. {VecEpilogueIterationCountCheck,
  7020. EPI.VectorTripCount} /* AdditionalBypass */);
  7021. AddRuntimeUnrollDisableMetaData(Lp);
  7022. return completeLoopSkeleton(Lp, OrigLoopID);
  7023. }
  7024. BasicBlock *
  7025. EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
  7026. Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
  7027. assert(EPI.TripCount &&
  7028. "Expected trip count to have been safed in the first pass.");
  7029. assert(
  7030. (!isa<Instruction>(EPI.TripCount) ||
  7031. DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
  7032. "saved trip count does not dominate insertion point.");
  7033. Value *TC = EPI.TripCount;
  7034. IRBuilder<> Builder(Insert->getTerminator());
  7035. Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
  7036. // Generate code to check if the loop's trip count is less than VF * UF of the
  7037. // vector epilogue loop.
  7038. auto P =
  7039. Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
  7040. Value *CheckMinIters = Builder.CreateICmp(
  7041. P, Count,
  7042. ConstantInt::get(Count->getType(),
  7043. EPI.EpilogueVF.getKnownMinValue() * EPI.EpilogueUF),
  7044. "min.epilog.iters.check");
  7045. ReplaceInstWithInst(
  7046. Insert->getTerminator(),
  7047. BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
  7048. LoopBypassBlocks.push_back(Insert);
  7049. return Insert;
  7050. }
  7051. void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
  7052. LLVM_DEBUG({
  7053. dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
  7054. << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
  7055. << ", Main Loop UF:" << EPI.MainLoopUF
  7056. << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
  7057. << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
  7058. });
  7059. }
  7060. void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
  7061. DEBUG_WITH_TYPE(VerboseDebug, {
  7062. dbgs() << "final fn:\n" << *Induction->getFunction() << "\n";
  7063. });
  7064. }
  7065. bool LoopVectorizationPlanner::getDecisionAndClampRange(
  7066. const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
  7067. assert(!Range.isEmpty() && "Trying to test an empty VF range.");
  7068. bool PredicateAtRangeStart = Predicate(Range.Start);
  7069. for (ElementCount TmpVF = Range.Start * 2;
  7070. ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
  7071. if (Predicate(TmpVF) != PredicateAtRangeStart) {
  7072. Range.End = TmpVF;
  7073. break;
  7074. }
  7075. return PredicateAtRangeStart;
  7076. }
  7077. /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
  7078. /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
  7079. /// of VF's starting at a given VF and extending it as much as possible. Each
  7080. /// vectorization decision can potentially shorten this sub-range during
  7081. /// buildVPlan().
  7082. void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
  7083. ElementCount MaxVF) {
  7084. auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
  7085. for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
  7086. VFRange SubRange = {VF, MaxVFPlusOne};
  7087. VPlans.push_back(buildVPlan(SubRange));
  7088. VF = SubRange.End;
  7089. }
  7090. }
  7091. VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
  7092. VPlanPtr &Plan) {
  7093. assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
  7094. // Look for cached value.
  7095. std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
  7096. EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
  7097. if (ECEntryIt != EdgeMaskCache.end())
  7098. return ECEntryIt->second;
  7099. VPValue *SrcMask = createBlockInMask(Src, Plan);
  7100. // The terminator has to be a branch inst!
  7101. BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
  7102. assert(BI && "Unexpected terminator found");
  7103. if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
  7104. return EdgeMaskCache[Edge] = SrcMask;
  7105. // If source is an exiting block, we know the exit edge is dynamically dead
  7106. // in the vector loop, and thus we don't need to restrict the mask. Avoid
  7107. // adding uses of an otherwise potentially dead instruction.
  7108. if (OrigLoop->isLoopExiting(Src))
  7109. return EdgeMaskCache[Edge] = SrcMask;
  7110. VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
  7111. assert(EdgeMask && "No Edge Mask found for condition");
  7112. if (BI->getSuccessor(0) != Dst)
  7113. EdgeMask = Builder.createNot(EdgeMask);
  7114. if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
  7115. // The condition is 'SrcMask && EdgeMask', which is equivalent to
  7116. // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
  7117. // The select version does not introduce new UB if SrcMask is false and
  7118. // EdgeMask is poison. Using 'and' here introduces undefined behavior.
  7119. VPValue *False = Plan->getOrAddVPValue(
  7120. ConstantInt::getFalse(BI->getCondition()->getType()));
  7121. EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
  7122. }
  7123. return EdgeMaskCache[Edge] = EdgeMask;
  7124. }
  7125. VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
  7126. assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
  7127. // Look for cached value.
  7128. BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
  7129. if (BCEntryIt != BlockMaskCache.end())
  7130. return BCEntryIt->second;
  7131. // All-one mask is modelled as no-mask following the convention for masked
  7132. // load/store/gather/scatter. Initialize BlockMask to no-mask.
  7133. VPValue *BlockMask = nullptr;
  7134. if (OrigLoop->getHeader() == BB) {
  7135. if (!CM.blockNeedsPredication(BB))
  7136. return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
  7137. // Create the block in mask as the first non-phi instruction in the block.
  7138. VPBuilder::InsertPointGuard Guard(Builder);
  7139. auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
  7140. Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
  7141. // Introduce the early-exit compare IV <= BTC to form header block mask.
  7142. // This is used instead of IV < TC because TC may wrap, unlike BTC.
  7143. // Start by constructing the desired canonical IV.
  7144. VPValue *IV = nullptr;
  7145. if (Legal->getPrimaryInduction())
  7146. IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
  7147. else {
  7148. auto IVRecipe = new VPWidenCanonicalIVRecipe();
  7149. Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
  7150. IV = IVRecipe->getVPValue();
  7151. }
  7152. VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
  7153. bool TailFolded = !CM.isScalarEpilogueAllowed();
  7154. if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
  7155. // While ActiveLaneMask is a binary op that consumes the loop tripcount
  7156. // as a second argument, we only pass the IV here and extract the
  7157. // tripcount from the transform state where codegen of the VP instructions
  7158. // happen.
  7159. BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
  7160. } else {
  7161. BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
  7162. }
  7163. return BlockMaskCache[BB] = BlockMask;
  7164. }
  7165. // This is the block mask. We OR all incoming edges.
  7166. for (auto *Predecessor : predecessors(BB)) {
  7167. VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
  7168. if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
  7169. return BlockMaskCache[BB] = EdgeMask;
  7170. if (!BlockMask) { // BlockMask has its initialized nullptr value.
  7171. BlockMask = EdgeMask;
  7172. continue;
  7173. }
  7174. BlockMask = Builder.createOr(BlockMask, EdgeMask);
  7175. }
  7176. return BlockMaskCache[BB] = BlockMask;
  7177. }
  7178. VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I, VFRange &Range,
  7179. VPlanPtr &Plan) {
  7180. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  7181. "Must be called with either a load or store");
  7182. auto willWiden = [&](ElementCount VF) -> bool {
  7183. if (VF.isScalar())
  7184. return false;
  7185. LoopVectorizationCostModel::InstWidening Decision =
  7186. CM.getWideningDecision(I, VF);
  7187. assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
  7188. "CM decision should be taken at this point.");
  7189. if (Decision == LoopVectorizationCostModel::CM_Interleave)
  7190. return true;
  7191. if (CM.isScalarAfterVectorization(I, VF) ||
  7192. CM.isProfitableToScalarize(I, VF))
  7193. return false;
  7194. return Decision != LoopVectorizationCostModel::CM_Scalarize;
  7195. };
  7196. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  7197. return nullptr;
  7198. VPValue *Mask = nullptr;
  7199. if (Legal->isMaskRequired(I))
  7200. Mask = createBlockInMask(I->getParent(), Plan);
  7201. VPValue *Addr = Plan->getOrAddVPValue(getLoadStorePointerOperand(I));
  7202. if (LoadInst *Load = dyn_cast<LoadInst>(I))
  7203. return new VPWidenMemoryInstructionRecipe(*Load, Addr, Mask);
  7204. StoreInst *Store = cast<StoreInst>(I);
  7205. VPValue *StoredValue = Plan->getOrAddVPValue(Store->getValueOperand());
  7206. return new VPWidenMemoryInstructionRecipe(*Store, Addr, StoredValue, Mask);
  7207. }
  7208. VPWidenIntOrFpInductionRecipe *
  7209. VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi, VPlan &Plan) const {
  7210. // Check if this is an integer or fp induction. If so, build the recipe that
  7211. // produces its scalar and vector values.
  7212. InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
  7213. if (II.getKind() == InductionDescriptor::IK_IntInduction ||
  7214. II.getKind() == InductionDescriptor::IK_FpInduction) {
  7215. VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
  7216. return new VPWidenIntOrFpInductionRecipe(Phi, Start);
  7217. }
  7218. return nullptr;
  7219. }
  7220. VPWidenIntOrFpInductionRecipe *
  7221. VPRecipeBuilder::tryToOptimizeInductionTruncate(TruncInst *I, VFRange &Range,
  7222. VPlan &Plan) const {
  7223. // Optimize the special case where the source is a constant integer
  7224. // induction variable. Notice that we can only optimize the 'trunc' case
  7225. // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
  7226. // (c) other casts depend on pointer size.
  7227. // Determine whether \p K is a truncation based on an induction variable that
  7228. // can be optimized.
  7229. auto isOptimizableIVTruncate =
  7230. [&](Instruction *K) -> std::function<bool(ElementCount)> {
  7231. return [=](ElementCount VF) -> bool {
  7232. return CM.isOptimizableIVTruncate(K, VF);
  7233. };
  7234. };
  7235. if (LoopVectorizationPlanner::getDecisionAndClampRange(
  7236. isOptimizableIVTruncate(I), Range)) {
  7237. InductionDescriptor II =
  7238. Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
  7239. VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
  7240. return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
  7241. Start, I);
  7242. }
  7243. return nullptr;
  7244. }
  7245. VPBlendRecipe *VPRecipeBuilder::tryToBlend(PHINode *Phi, VPlanPtr &Plan) {
  7246. // We know that all PHIs in non-header blocks are converted into selects, so
  7247. // we don't have to worry about the insertion order and we can just use the
  7248. // builder. At this point we generate the predication tree. There may be
  7249. // duplications since this is a simple recursive scan, but future
  7250. // optimizations will clean it up.
  7251. SmallVector<VPValue *, 2> Operands;
  7252. unsigned NumIncoming = Phi->getNumIncomingValues();
  7253. for (unsigned In = 0; In < NumIncoming; In++) {
  7254. VPValue *EdgeMask =
  7255. createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
  7256. assert((EdgeMask || NumIncoming == 1) &&
  7257. "Multiple predecessors with one having a full mask");
  7258. Operands.push_back(Plan->getOrAddVPValue(Phi->getIncomingValue(In)));
  7259. if (EdgeMask)
  7260. Operands.push_back(EdgeMask);
  7261. }
  7262. return new VPBlendRecipe(Phi, Operands);
  7263. }
  7264. VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI, VFRange &Range,
  7265. VPlan &Plan) const {
  7266. bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
  7267. [this, CI](ElementCount VF) {
  7268. return CM.isScalarWithPredication(CI, VF);
  7269. },
  7270. Range);
  7271. if (IsPredicated)
  7272. return nullptr;
  7273. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  7274. if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
  7275. ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
  7276. ID == Intrinsic::pseudoprobe ||
  7277. ID == Intrinsic::experimental_noalias_scope_decl))
  7278. return nullptr;
  7279. auto willWiden = [&](ElementCount VF) -> bool {
  7280. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  7281. // The following case may be scalarized depending on the VF.
  7282. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  7283. // version of the instruction.
  7284. // Is it beneficial to perform intrinsic call compared to lib call?
  7285. bool NeedToScalarize = false;
  7286. InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
  7287. InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
  7288. bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
  7289. assert(IntrinsicCost.isValid() && CallCost.isValid() &&
  7290. "Cannot have invalid costs while widening");
  7291. return UseVectorIntrinsic || !NeedToScalarize;
  7292. };
  7293. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  7294. return nullptr;
  7295. return new VPWidenCallRecipe(*CI, Plan.mapToVPValues(CI->arg_operands()));
  7296. }
  7297. bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
  7298. assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
  7299. !isa<StoreInst>(I) && "Instruction should have been handled earlier");
  7300. // Instruction should be widened, unless it is scalar after vectorization,
  7301. // scalarization is profitable or it is predicated.
  7302. auto WillScalarize = [this, I](ElementCount VF) -> bool {
  7303. return CM.isScalarAfterVectorization(I, VF) ||
  7304. CM.isProfitableToScalarize(I, VF) ||
  7305. CM.isScalarWithPredication(I, VF);
  7306. };
  7307. return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
  7308. Range);
  7309. }
  7310. VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I, VPlan &Plan) const {
  7311. auto IsVectorizableOpcode = [](unsigned Opcode) {
  7312. switch (Opcode) {
  7313. case Instruction::Add:
  7314. case Instruction::And:
  7315. case Instruction::AShr:
  7316. case Instruction::BitCast:
  7317. case Instruction::FAdd:
  7318. case Instruction::FCmp:
  7319. case Instruction::FDiv:
  7320. case Instruction::FMul:
  7321. case Instruction::FNeg:
  7322. case Instruction::FPExt:
  7323. case Instruction::FPToSI:
  7324. case Instruction::FPToUI:
  7325. case Instruction::FPTrunc:
  7326. case Instruction::FRem:
  7327. case Instruction::FSub:
  7328. case Instruction::ICmp:
  7329. case Instruction::IntToPtr:
  7330. case Instruction::LShr:
  7331. case Instruction::Mul:
  7332. case Instruction::Or:
  7333. case Instruction::PtrToInt:
  7334. case Instruction::SDiv:
  7335. case Instruction::Select:
  7336. case Instruction::SExt:
  7337. case Instruction::Shl:
  7338. case Instruction::SIToFP:
  7339. case Instruction::SRem:
  7340. case Instruction::Sub:
  7341. case Instruction::Trunc:
  7342. case Instruction::UDiv:
  7343. case Instruction::UIToFP:
  7344. case Instruction::URem:
  7345. case Instruction::Xor:
  7346. case Instruction::ZExt:
  7347. return true;
  7348. }
  7349. return false;
  7350. };
  7351. if (!IsVectorizableOpcode(I->getOpcode()))
  7352. return nullptr;
  7353. // Success: widen this instruction.
  7354. return new VPWidenRecipe(*I, Plan.mapToVPValues(I->operands()));
  7355. }
  7356. VPBasicBlock *VPRecipeBuilder::handleReplication(
  7357. Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
  7358. DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe,
  7359. VPlanPtr &Plan) {
  7360. bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
  7361. [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
  7362. Range);
  7363. bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
  7364. [&](ElementCount VF) { return CM.isScalarWithPredication(I, VF); },
  7365. Range);
  7366. auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
  7367. IsUniform, IsPredicated);
  7368. setRecipe(I, Recipe);
  7369. Plan->addVPValue(I, Recipe);
  7370. // Find if I uses a predicated instruction. If so, it will use its scalar
  7371. // value. Avoid hoisting the insert-element which packs the scalar value into
  7372. // a vector value, as that happens iff all users use the vector value.
  7373. for (auto &Op : I->operands())
  7374. if (auto *PredInst = dyn_cast<Instruction>(Op))
  7375. if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end())
  7376. PredInst2Recipe[PredInst]->setAlsoPack(false);
  7377. // Finalize the recipe for Instr, first if it is not predicated.
  7378. if (!IsPredicated) {
  7379. LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
  7380. VPBB->appendRecipe(Recipe);
  7381. return VPBB;
  7382. }
  7383. LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
  7384. assert(VPBB->getSuccessors().empty() &&
  7385. "VPBB has successors when handling predicated replication.");
  7386. // Record predicated instructions for above packing optimizations.
  7387. PredInst2Recipe[I] = Recipe;
  7388. VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
  7389. VPBlockUtils::insertBlockAfter(Region, VPBB);
  7390. auto *RegSucc = new VPBasicBlock();
  7391. VPBlockUtils::insertBlockAfter(RegSucc, Region);
  7392. return RegSucc;
  7393. }
  7394. VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
  7395. VPRecipeBase *PredRecipe,
  7396. VPlanPtr &Plan) {
  7397. // Instructions marked for predication are replicated and placed under an
  7398. // if-then construct to prevent side-effects.
  7399. // Generate recipes to compute the block mask for this region.
  7400. VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
  7401. // Build the triangular if-then region.
  7402. std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
  7403. assert(Instr->getParent() && "Predicated instruction not in any basic block");
  7404. auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
  7405. auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
  7406. auto *PHIRecipe = Instr->getType()->isVoidTy()
  7407. ? nullptr
  7408. : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
  7409. auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
  7410. auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
  7411. VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
  7412. // Note: first set Entry as region entry and then connect successors starting
  7413. // from it in order, to propagate the "parent" of each VPBasicBlock.
  7414. VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
  7415. VPBlockUtils::connectBlocks(Pred, Exit);
  7416. return Region;
  7417. }
  7418. VPRecipeBase *VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
  7419. VFRange &Range,
  7420. VPlanPtr &Plan) {
  7421. // First, check for specific widening recipes that deal with calls, memory
  7422. // operations, inductions and Phi nodes.
  7423. if (auto *CI = dyn_cast<CallInst>(Instr))
  7424. return tryToWidenCall(CI, Range, *Plan);
  7425. if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
  7426. return tryToWidenMemory(Instr, Range, Plan);
  7427. VPRecipeBase *Recipe;
  7428. if (auto Phi = dyn_cast<PHINode>(Instr)) {
  7429. if (Phi->getParent() != OrigLoop->getHeader())
  7430. return tryToBlend(Phi, Plan);
  7431. if ((Recipe = tryToOptimizeInductionPHI(Phi, *Plan)))
  7432. return Recipe;
  7433. if (Legal->isReductionVariable(Phi)) {
  7434. RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
  7435. VPValue *StartV =
  7436. Plan->getOrAddVPValue(RdxDesc.getRecurrenceStartValue());
  7437. return new VPWidenPHIRecipe(Phi, RdxDesc, *StartV);
  7438. }
  7439. return new VPWidenPHIRecipe(Phi);
  7440. }
  7441. if (isa<TruncInst>(Instr) && (Recipe = tryToOptimizeInductionTruncate(
  7442. cast<TruncInst>(Instr), Range, *Plan)))
  7443. return Recipe;
  7444. if (!shouldWiden(Instr, Range))
  7445. return nullptr;
  7446. if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
  7447. return new VPWidenGEPRecipe(GEP, Plan->mapToVPValues(GEP->operands()),
  7448. OrigLoop);
  7449. if (auto *SI = dyn_cast<SelectInst>(Instr)) {
  7450. bool InvariantCond =
  7451. PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
  7452. return new VPWidenSelectRecipe(*SI, Plan->mapToVPValues(SI->operands()),
  7453. InvariantCond);
  7454. }
  7455. return tryToWiden(Instr, *Plan);
  7456. }
  7457. void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
  7458. ElementCount MaxVF) {
  7459. assert(OrigLoop->isInnermost() && "Inner loop expected.");
  7460. // Collect instructions from the original loop that will become trivially dead
  7461. // in the vectorized loop. We don't need to vectorize these instructions. For
  7462. // example, original induction update instructions can become dead because we
  7463. // separately emit induction "steps" when generating code for the new loop.
  7464. // Similarly, we create a new latch condition when setting up the structure
  7465. // of the new loop, so the old one can become dead.
  7466. SmallPtrSet<Instruction *, 4> DeadInstructions;
  7467. collectTriviallyDeadInstructions(DeadInstructions);
  7468. // Add assume instructions we need to drop to DeadInstructions, to prevent
  7469. // them from being added to the VPlan.
  7470. // TODO: We only need to drop assumes in blocks that get flattend. If the
  7471. // control flow is preserved, we should keep them.
  7472. auto &ConditionalAssumes = Legal->getConditionalAssumes();
  7473. DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
  7474. DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
  7475. // Dead instructions do not need sinking. Remove them from SinkAfter.
  7476. for (Instruction *I : DeadInstructions)
  7477. SinkAfter.erase(I);
  7478. auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
  7479. for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
  7480. VFRange SubRange = {VF, MaxVFPlusOne};
  7481. VPlans.push_back(
  7482. buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
  7483. VF = SubRange.End;
  7484. }
  7485. }
  7486. VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
  7487. VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
  7488. const DenseMap<Instruction *, Instruction *> &SinkAfter) {
  7489. // Hold a mapping from predicated instructions to their recipes, in order to
  7490. // fix their AlsoPack behavior if a user is determined to replicate and use a
  7491. // scalar instead of vector value.
  7492. DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe;
  7493. SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
  7494. VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
  7495. // ---------------------------------------------------------------------------
  7496. // Pre-construction: record ingredients whose recipes we'll need to further
  7497. // process after constructing the initial VPlan.
  7498. // ---------------------------------------------------------------------------
  7499. // Mark instructions we'll need to sink later and their targets as
  7500. // ingredients whose recipe we'll need to record.
  7501. for (auto &Entry : SinkAfter) {
  7502. RecipeBuilder.recordRecipeOf(Entry.first);
  7503. RecipeBuilder.recordRecipeOf(Entry.second);
  7504. }
  7505. for (auto &Reduction : CM.getInLoopReductionChains()) {
  7506. PHINode *Phi = Reduction.first;
  7507. RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
  7508. const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
  7509. RecipeBuilder.recordRecipeOf(Phi);
  7510. for (auto &R : ReductionOperations) {
  7511. RecipeBuilder.recordRecipeOf(R);
  7512. // For min/max reducitons, where we have a pair of icmp/select, we also
  7513. // need to record the ICmp recipe, so it can be removed later.
  7514. if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
  7515. RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
  7516. }
  7517. }
  7518. // For each interleave group which is relevant for this (possibly trimmed)
  7519. // Range, add it to the set of groups to be later applied to the VPlan and add
  7520. // placeholders for its members' Recipes which we'll be replacing with a
  7521. // single VPInterleaveRecipe.
  7522. for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
  7523. auto applyIG = [IG, this](ElementCount VF) -> bool {
  7524. return (VF.isVector() && // Query is illegal for VF == 1
  7525. CM.getWideningDecision(IG->getInsertPos(), VF) ==
  7526. LoopVectorizationCostModel::CM_Interleave);
  7527. };
  7528. if (!getDecisionAndClampRange(applyIG, Range))
  7529. continue;
  7530. InterleaveGroups.insert(IG);
  7531. for (unsigned i = 0; i < IG->getFactor(); i++)
  7532. if (Instruction *Member = IG->getMember(i))
  7533. RecipeBuilder.recordRecipeOf(Member);
  7534. };
  7535. // ---------------------------------------------------------------------------
  7536. // Build initial VPlan: Scan the body of the loop in a topological order to
  7537. // visit each basic block after having visited its predecessor basic blocks.
  7538. // ---------------------------------------------------------------------------
  7539. // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
  7540. auto Plan = std::make_unique<VPlan>();
  7541. VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
  7542. Plan->setEntry(VPBB);
  7543. // Scan the body of the loop in a topological order to visit each basic block
  7544. // after having visited its predecessor basic blocks.
  7545. LoopBlocksDFS DFS(OrigLoop);
  7546. DFS.perform(LI);
  7547. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  7548. // Relevant instructions from basic block BB will be grouped into VPRecipe
  7549. // ingredients and fill a new VPBasicBlock.
  7550. unsigned VPBBsForBB = 0;
  7551. auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
  7552. VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
  7553. VPBB = FirstVPBBForBB;
  7554. Builder.setInsertPoint(VPBB);
  7555. // Introduce each ingredient into VPlan.
  7556. // TODO: Model and preserve debug instrinsics in VPlan.
  7557. for (Instruction &I : BB->instructionsWithoutDebug()) {
  7558. Instruction *Instr = &I;
  7559. // First filter out irrelevant instructions, to ensure no recipes are
  7560. // built for them.
  7561. if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
  7562. continue;
  7563. if (auto Recipe =
  7564. RecipeBuilder.tryToCreateWidenRecipe(Instr, Range, Plan)) {
  7565. for (auto *Def : Recipe->definedValues()) {
  7566. auto *UV = Def->getUnderlyingValue();
  7567. Plan->addVPValue(UV, Def);
  7568. }
  7569. RecipeBuilder.setRecipe(Instr, Recipe);
  7570. VPBB->appendRecipe(Recipe);
  7571. continue;
  7572. }
  7573. // Otherwise, if all widening options failed, Instruction is to be
  7574. // replicated. This may create a successor for VPBB.
  7575. VPBasicBlock *NextVPBB = RecipeBuilder.handleReplication(
  7576. Instr, Range, VPBB, PredInst2Recipe, Plan);
  7577. if (NextVPBB != VPBB) {
  7578. VPBB = NextVPBB;
  7579. VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
  7580. : "");
  7581. }
  7582. }
  7583. }
  7584. // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
  7585. // may also be empty, such as the last one VPBB, reflecting original
  7586. // basic-blocks with no recipes.
  7587. VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
  7588. assert(PreEntry->empty() && "Expecting empty pre-entry block.");
  7589. VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
  7590. VPBlockUtils::disconnectBlocks(PreEntry, Entry);
  7591. delete PreEntry;
  7592. // ---------------------------------------------------------------------------
  7593. // Transform initial VPlan: Apply previously taken decisions, in order, to
  7594. // bring the VPlan to its final state.
  7595. // ---------------------------------------------------------------------------
  7596. // Apply Sink-After legal constraints.
  7597. for (auto &Entry : SinkAfter) {
  7598. VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
  7599. VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
  7600. // If the target is in a replication region, make sure to move Sink to the
  7601. // block after it, not into the replication region itself.
  7602. if (auto *Region =
  7603. dyn_cast_or_null<VPRegionBlock>(Target->getParent()->getParent())) {
  7604. if (Region->isReplicator()) {
  7605. assert(Region->getNumSuccessors() == 1 && "Expected SESE region!");
  7606. VPBasicBlock *NextBlock =
  7607. cast<VPBasicBlock>(Region->getSuccessors().front());
  7608. Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
  7609. continue;
  7610. }
  7611. }
  7612. Sink->moveAfter(Target);
  7613. }
  7614. // Interleave memory: for each Interleave Group we marked earlier as relevant
  7615. // for this VPlan, replace the Recipes widening its memory instructions with a
  7616. // single VPInterleaveRecipe at its insertion point.
  7617. for (auto IG : InterleaveGroups) {
  7618. auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
  7619. RecipeBuilder.getRecipe(IG->getInsertPos()));
  7620. SmallVector<VPValue *, 4> StoredValues;
  7621. for (unsigned i = 0; i < IG->getFactor(); ++i)
  7622. if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i)))
  7623. StoredValues.push_back(Plan->getOrAddVPValue(SI->getOperand(0)));
  7624. auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
  7625. Recipe->getMask());
  7626. VPIG->insertBefore(Recipe);
  7627. unsigned J = 0;
  7628. for (unsigned i = 0; i < IG->getFactor(); ++i)
  7629. if (Instruction *Member = IG->getMember(i)) {
  7630. if (!Member->getType()->isVoidTy()) {
  7631. VPValue *OriginalV = Plan->getVPValue(Member);
  7632. Plan->removeVPValueFor(Member);
  7633. Plan->addVPValue(Member, VPIG->getVPValue(J));
  7634. OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
  7635. J++;
  7636. }
  7637. RecipeBuilder.getRecipe(Member)->eraseFromParent();
  7638. }
  7639. }
  7640. // Adjust the recipes for any inloop reductions.
  7641. if (Range.Start.isVector())
  7642. adjustRecipesForInLoopReductions(Plan, RecipeBuilder);
  7643. // Finally, if tail is folded by masking, introduce selects between the phi
  7644. // and the live-out instruction of each reduction, at the end of the latch.
  7645. if (CM.foldTailByMasking() && !Legal->getReductionVars().empty()) {
  7646. Builder.setInsertPoint(VPBB);
  7647. auto *Cond = RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
  7648. for (auto &Reduction : Legal->getReductionVars()) {
  7649. if (CM.isInLoopReduction(Reduction.first))
  7650. continue;
  7651. VPValue *Phi = Plan->getOrAddVPValue(Reduction.first);
  7652. VPValue *Red = Plan->getOrAddVPValue(Reduction.second.getLoopExitInstr());
  7653. Builder.createNaryOp(Instruction::Select, {Cond, Red, Phi});
  7654. }
  7655. }
  7656. std::string PlanName;
  7657. raw_string_ostream RSO(PlanName);
  7658. ElementCount VF = Range.Start;
  7659. Plan->addVF(VF);
  7660. RSO << "Initial VPlan for VF={" << VF;
  7661. for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
  7662. Plan->addVF(VF);
  7663. RSO << "," << VF;
  7664. }
  7665. RSO << "},UF>=1";
  7666. RSO.flush();
  7667. Plan->setName(PlanName);
  7668. return Plan;
  7669. }
  7670. VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
  7671. // Outer loop handling: They may require CFG and instruction level
  7672. // transformations before even evaluating whether vectorization is profitable.
  7673. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  7674. // the vectorization pipeline.
  7675. assert(!OrigLoop->isInnermost());
  7676. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  7677. // Create new empty VPlan
  7678. auto Plan = std::make_unique<VPlan>();
  7679. // Build hierarchical CFG
  7680. VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
  7681. HCFGBuilder.buildHierarchicalCFG();
  7682. for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
  7683. VF *= 2)
  7684. Plan->addVF(VF);
  7685. if (EnableVPlanPredication) {
  7686. VPlanPredicator VPP(*Plan);
  7687. VPP.predicate();
  7688. // Avoid running transformation to recipes until masked code generation in
  7689. // VPlan-native path is in place.
  7690. return Plan;
  7691. }
  7692. SmallPtrSet<Instruction *, 1> DeadInstructions;
  7693. VPlanTransforms::VPInstructionsToVPRecipes(
  7694. OrigLoop, Plan, Legal->getInductionVars(), DeadInstructions);
  7695. return Plan;
  7696. }
  7697. // Adjust the recipes for any inloop reductions. The chain of instructions
  7698. // leading from the loop exit instr to the phi need to be converted to
  7699. // reductions, with one operand being vector and the other being the scalar
  7700. // reduction chain.
  7701. void LoopVectorizationPlanner::adjustRecipesForInLoopReductions(
  7702. VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder) {
  7703. for (auto &Reduction : CM.getInLoopReductionChains()) {
  7704. PHINode *Phi = Reduction.first;
  7705. RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
  7706. const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
  7707. // ReductionOperations are orders top-down from the phi's use to the
  7708. // LoopExitValue. We keep a track of the previous item (the Chain) to tell
  7709. // which of the two operands will remain scalar and which will be reduced.
  7710. // For minmax the chain will be the select instructions.
  7711. Instruction *Chain = Phi;
  7712. for (Instruction *R : ReductionOperations) {
  7713. VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
  7714. RecurKind Kind = RdxDesc.getRecurrenceKind();
  7715. VPValue *ChainOp = Plan->getVPValue(Chain);
  7716. unsigned FirstOpId;
  7717. if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
  7718. assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
  7719. "Expected to replace a VPWidenSelectSC");
  7720. FirstOpId = 1;
  7721. } else {
  7722. assert(isa<VPWidenRecipe>(WidenRecipe) &&
  7723. "Expected to replace a VPWidenSC");
  7724. FirstOpId = 0;
  7725. }
  7726. unsigned VecOpId =
  7727. R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
  7728. VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
  7729. auto *CondOp = CM.foldTailByMasking()
  7730. ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
  7731. : nullptr;
  7732. VPReductionRecipe *RedRecipe = new VPReductionRecipe(
  7733. &RdxDesc, R, ChainOp, VecOp, CondOp, Legal->hasFunNoNaNAttr(), TTI);
  7734. WidenRecipe->getVPValue()->replaceAllUsesWith(RedRecipe);
  7735. Plan->removeVPValueFor(R);
  7736. Plan->addVPValue(R, RedRecipe);
  7737. WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
  7738. WidenRecipe->getVPValue()->replaceAllUsesWith(RedRecipe);
  7739. WidenRecipe->eraseFromParent();
  7740. if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
  7741. VPRecipeBase *CompareRecipe =
  7742. RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
  7743. assert(isa<VPWidenRecipe>(CompareRecipe) &&
  7744. "Expected to replace a VPWidenSC");
  7745. assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
  7746. "Expected no remaining users");
  7747. CompareRecipe->eraseFromParent();
  7748. }
  7749. Chain = R;
  7750. }
  7751. }
  7752. }
  7753. Value* LoopVectorizationPlanner::VPCallbackILV::
  7754. getOrCreateVectorValues(Value *V, unsigned Part) {
  7755. return ILV.getOrCreateVectorValue(V, Part);
  7756. }
  7757. Value *LoopVectorizationPlanner::VPCallbackILV::getOrCreateScalarValue(
  7758. Value *V, const VPIteration &Instance) {
  7759. return ILV.getOrCreateScalarValue(V, Instance);
  7760. }
  7761. void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
  7762. VPSlotTracker &SlotTracker) const {
  7763. O << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
  7764. IG->getInsertPos()->printAsOperand(O, false);
  7765. O << ", ";
  7766. getAddr()->printAsOperand(O, SlotTracker);
  7767. VPValue *Mask = getMask();
  7768. if (Mask) {
  7769. O << ", ";
  7770. Mask->printAsOperand(O, SlotTracker);
  7771. }
  7772. for (unsigned i = 0; i < IG->getFactor(); ++i)
  7773. if (Instruction *I = IG->getMember(i))
  7774. O << "\\l\" +\n" << Indent << "\" " << VPlanIngredient(I) << " " << i;
  7775. }
  7776. void VPWidenCallRecipe::execute(VPTransformState &State) {
  7777. State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
  7778. *this, State);
  7779. }
  7780. void VPWidenSelectRecipe::execute(VPTransformState &State) {
  7781. State.ILV->widenSelectInstruction(*cast<SelectInst>(getUnderlyingInstr()),
  7782. this, *this, InvariantCond, State);
  7783. }
  7784. void VPWidenRecipe::execute(VPTransformState &State) {
  7785. State.ILV->widenInstruction(*getUnderlyingInstr(), this, *this, State);
  7786. }
  7787. void VPWidenGEPRecipe::execute(VPTransformState &State) {
  7788. State.ILV->widenGEP(cast<GetElementPtrInst>(getUnderlyingInstr()), this,
  7789. *this, State.UF, State.VF, IsPtrLoopInvariant,
  7790. IsIndexLoopInvariant, State);
  7791. }
  7792. void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
  7793. assert(!State.Instance && "Int or FP induction being replicated.");
  7794. State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
  7795. Trunc);
  7796. }
  7797. void VPWidenPHIRecipe::execute(VPTransformState &State) {
  7798. Value *StartV =
  7799. getStartValue() ? getStartValue()->getLiveInIRValue() : nullptr;
  7800. State.ILV->widenPHIInstruction(Phi, RdxDesc, StartV, State.UF, State.VF);
  7801. }
  7802. void VPBlendRecipe::execute(VPTransformState &State) {
  7803. State.ILV->setDebugLocFromInst(State.Builder, Phi);
  7804. // We know that all PHIs in non-header blocks are converted into
  7805. // selects, so we don't have to worry about the insertion order and we
  7806. // can just use the builder.
  7807. // At this point we generate the predication tree. There may be
  7808. // duplications since this is a simple recursive scan, but future
  7809. // optimizations will clean it up.
  7810. unsigned NumIncoming = getNumIncomingValues();
  7811. // Generate a sequence of selects of the form:
  7812. // SELECT(Mask3, In3,
  7813. // SELECT(Mask2, In2,
  7814. // SELECT(Mask1, In1,
  7815. // In0)))
  7816. // Note that Mask0 is never used: lanes for which no path reaches this phi and
  7817. // are essentially undef are taken from In0.
  7818. InnerLoopVectorizer::VectorParts Entry(State.UF);
  7819. for (unsigned In = 0; In < NumIncoming; ++In) {
  7820. for (unsigned Part = 0; Part < State.UF; ++Part) {
  7821. // We might have single edge PHIs (blocks) - use an identity
  7822. // 'select' for the first PHI operand.
  7823. Value *In0 = State.get(getIncomingValue(In), Part);
  7824. if (In == 0)
  7825. Entry[Part] = In0; // Initialize with the first incoming value.
  7826. else {
  7827. // Select between the current value and the previous incoming edge
  7828. // based on the incoming mask.
  7829. Value *Cond = State.get(getMask(In), Part);
  7830. Entry[Part] =
  7831. State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
  7832. }
  7833. }
  7834. }
  7835. for (unsigned Part = 0; Part < State.UF; ++Part)
  7836. State.ValueMap.setVectorValue(Phi, Part, Entry[Part]);
  7837. }
  7838. void VPInterleaveRecipe::execute(VPTransformState &State) {
  7839. assert(!State.Instance && "Interleave group being replicated.");
  7840. State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
  7841. getStoredValues(), getMask());
  7842. }
  7843. void VPReductionRecipe::execute(VPTransformState &State) {
  7844. assert(!State.Instance && "Reduction being replicated.");
  7845. for (unsigned Part = 0; Part < State.UF; ++Part) {
  7846. RecurKind Kind = RdxDesc->getRecurrenceKind();
  7847. Value *NewVecOp = State.get(getVecOp(), Part);
  7848. if (VPValue *Cond = getCondOp()) {
  7849. Value *NewCond = State.get(Cond, Part);
  7850. VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
  7851. Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
  7852. Kind, VecTy->getElementType());
  7853. Constant *IdenVec =
  7854. ConstantVector::getSplat(VecTy->getElementCount(), Iden);
  7855. Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
  7856. NewVecOp = Select;
  7857. }
  7858. Value *NewRed =
  7859. createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
  7860. Value *PrevInChain = State.get(getChainOp(), Part);
  7861. Value *NextInChain;
  7862. if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
  7863. NextInChain =
  7864. createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
  7865. NewRed, PrevInChain);
  7866. } else {
  7867. NextInChain = State.Builder.CreateBinOp(
  7868. (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(), NewRed,
  7869. PrevInChain);
  7870. }
  7871. State.set(this, getUnderlyingInstr(), NextInChain, Part);
  7872. }
  7873. }
  7874. void VPReplicateRecipe::execute(VPTransformState &State) {
  7875. if (State.Instance) { // Generate a single instance.
  7876. assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
  7877. State.ILV->scalarizeInstruction(getUnderlyingInstr(), *this,
  7878. *State.Instance, IsPredicated, State);
  7879. // Insert scalar instance packing it into a vector.
  7880. if (AlsoPack && State.VF.isVector()) {
  7881. // If we're constructing lane 0, initialize to start from poison.
  7882. if (State.Instance->Lane == 0) {
  7883. assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
  7884. Value *Poison = PoisonValue::get(
  7885. VectorType::get(getUnderlyingValue()->getType(), State.VF));
  7886. State.ValueMap.setVectorValue(getUnderlyingInstr(),
  7887. State.Instance->Part, Poison);
  7888. }
  7889. State.ILV->packScalarIntoVectorValue(getUnderlyingInstr(),
  7890. *State.Instance);
  7891. }
  7892. return;
  7893. }
  7894. // Generate scalar instances for all VF lanes of all UF parts, unless the
  7895. // instruction is uniform inwhich case generate only the first lane for each
  7896. // of the UF parts.
  7897. unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
  7898. assert((!State.VF.isScalable() || IsUniform) &&
  7899. "Can't scalarize a scalable vector");
  7900. for (unsigned Part = 0; Part < State.UF; ++Part)
  7901. for (unsigned Lane = 0; Lane < EndLane; ++Lane)
  7902. State.ILV->scalarizeInstruction(getUnderlyingInstr(), *this, {Part, Lane},
  7903. IsPredicated, State);
  7904. }
  7905. void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
  7906. assert(State.Instance && "Branch on Mask works only on single instance.");
  7907. unsigned Part = State.Instance->Part;
  7908. unsigned Lane = State.Instance->Lane;
  7909. Value *ConditionBit = nullptr;
  7910. VPValue *BlockInMask = getMask();
  7911. if (BlockInMask) {
  7912. ConditionBit = State.get(BlockInMask, Part);
  7913. if (ConditionBit->getType()->isVectorTy())
  7914. ConditionBit = State.Builder.CreateExtractElement(
  7915. ConditionBit, State.Builder.getInt32(Lane));
  7916. } else // Block in mask is all-one.
  7917. ConditionBit = State.Builder.getTrue();
  7918. // Replace the temporary unreachable terminator with a new conditional branch,
  7919. // whose two destinations will be set later when they are created.
  7920. auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
  7921. assert(isa<UnreachableInst>(CurrentTerminator) &&
  7922. "Expected to replace unreachable terminator with conditional branch.");
  7923. auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
  7924. CondBr->setSuccessor(0, nullptr);
  7925. ReplaceInstWithInst(CurrentTerminator, CondBr);
  7926. }
  7927. void VPPredInstPHIRecipe::execute(VPTransformState &State) {
  7928. assert(State.Instance && "Predicated instruction PHI works per instance.");
  7929. Instruction *ScalarPredInst =
  7930. cast<Instruction>(State.get(getOperand(0), *State.Instance));
  7931. BasicBlock *PredicatedBB = ScalarPredInst->getParent();
  7932. BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
  7933. assert(PredicatingBB && "Predicated block has no single predecessor.");
  7934. // By current pack/unpack logic we need to generate only a single phi node: if
  7935. // a vector value for the predicated instruction exists at this point it means
  7936. // the instruction has vector users only, and a phi for the vector value is
  7937. // needed. In this case the recipe of the predicated instruction is marked to
  7938. // also do that packing, thereby "hoisting" the insert-element sequence.
  7939. // Otherwise, a phi node for the scalar value is needed.
  7940. unsigned Part = State.Instance->Part;
  7941. Instruction *PredInst =
  7942. cast<Instruction>(getOperand(0)->getUnderlyingValue());
  7943. if (State.ValueMap.hasVectorValue(PredInst, Part)) {
  7944. Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part);
  7945. InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
  7946. PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
  7947. VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
  7948. VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
  7949. State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache.
  7950. } else {
  7951. Type *PredInstType = PredInst->getType();
  7952. PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
  7953. Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()), PredicatingBB);
  7954. Phi->addIncoming(ScalarPredInst, PredicatedBB);
  7955. State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi);
  7956. }
  7957. }
  7958. void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
  7959. VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
  7960. State.ILV->vectorizeMemoryInstruction(&Ingredient, State,
  7961. StoredValue ? nullptr : getVPValue(),
  7962. getAddr(), StoredValue, getMask());
  7963. }
  7964. // Determine how to lower the scalar epilogue, which depends on 1) optimising
  7965. // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
  7966. // predication, and 4) a TTI hook that analyses whether the loop is suitable
  7967. // for predication.
  7968. static ScalarEpilogueLowering getScalarEpilogueLowering(
  7969. Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
  7970. BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
  7971. AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
  7972. LoopVectorizationLegality &LVL) {
  7973. // 1) OptSize takes precedence over all other options, i.e. if this is set,
  7974. // don't look at hints or options, and don't request a scalar epilogue.
  7975. // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
  7976. // LoopAccessInfo (due to code dependency and not being able to reliably get
  7977. // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
  7978. // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
  7979. // versioning when the vectorization is forced, unlike hasOptSize. So revert
  7980. // back to the old way and vectorize with versioning when forced. See D81345.)
  7981. if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
  7982. PGSOQueryType::IRPass) &&
  7983. Hints.getForce() != LoopVectorizeHints::FK_Enabled))
  7984. return CM_ScalarEpilogueNotAllowedOptSize;
  7985. // 2) If set, obey the directives
  7986. if (PreferPredicateOverEpilogue.getNumOccurrences()) {
  7987. switch (PreferPredicateOverEpilogue) {
  7988. case PreferPredicateTy::ScalarEpilogue:
  7989. return CM_ScalarEpilogueAllowed;
  7990. case PreferPredicateTy::PredicateElseScalarEpilogue:
  7991. return CM_ScalarEpilogueNotNeededUsePredicate;
  7992. case PreferPredicateTy::PredicateOrDontVectorize:
  7993. return CM_ScalarEpilogueNotAllowedUsePredicate;
  7994. };
  7995. }
  7996. // 3) If set, obey the hints
  7997. switch (Hints.getPredicate()) {
  7998. case LoopVectorizeHints::FK_Enabled:
  7999. return CM_ScalarEpilogueNotNeededUsePredicate;
  8000. case LoopVectorizeHints::FK_Disabled:
  8001. return CM_ScalarEpilogueAllowed;
  8002. };
  8003. // 4) if the TTI hook indicates this is profitable, request predication.
  8004. if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
  8005. LVL.getLAI()))
  8006. return CM_ScalarEpilogueNotNeededUsePredicate;
  8007. return CM_ScalarEpilogueAllowed;
  8008. }
  8009. void VPTransformState::set(VPValue *Def, Value *IRDef, Value *V,
  8010. unsigned Part) {
  8011. set(Def, V, Part);
  8012. ILV->setVectorValue(IRDef, Part, V);
  8013. }
  8014. // Process the loop in the VPlan-native vectorization path. This path builds
  8015. // VPlan upfront in the vectorization pipeline, which allows to apply
  8016. // VPlan-to-VPlan transformations from the very beginning without modifying the
  8017. // input LLVM IR.
  8018. static bool processLoopInVPlanNativePath(
  8019. Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
  8020. LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
  8021. TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
  8022. OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
  8023. ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints) {
  8024. if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
  8025. LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
  8026. return false;
  8027. }
  8028. assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
  8029. Function *F = L->getHeader()->getParent();
  8030. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
  8031. ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
  8032. F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
  8033. LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
  8034. &Hints, IAI);
  8035. // Use the planner for outer loop vectorization.
  8036. // TODO: CM is not used at this point inside the planner. Turn CM into an
  8037. // optional argument if we don't need it in the future.
  8038. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE);
  8039. // Get user vectorization factor.
  8040. ElementCount UserVF = Hints.getWidth();
  8041. // Plan how to best vectorize, return the best VF and its cost.
  8042. const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
  8043. // If we are stress testing VPlan builds, do not attempt to generate vector
  8044. // code. Masked vector code generation support will follow soon.
  8045. // Also, do not attempt to vectorize if no vector code will be produced.
  8046. if (VPlanBuildStressTest || EnableVPlanPredication ||
  8047. VectorizationFactor::Disabled() == VF)
  8048. return false;
  8049. LVP.setBestPlan(VF.Width, 1);
  8050. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
  8051. &CM, BFI, PSI);
  8052. LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
  8053. << L->getHeader()->getParent()->getName() << "\"\n");
  8054. LVP.executePlan(LB, DT);
  8055. // Mark the loop as already vectorized to avoid vectorizing again.
  8056. Hints.setAlreadyVectorized();
  8057. assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
  8058. return true;
  8059. }
  8060. LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
  8061. : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
  8062. !EnableLoopInterleaving),
  8063. VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
  8064. !EnableLoopVectorization) {}
  8065. bool LoopVectorizePass::processLoop(Loop *L) {
  8066. assert((EnableVPlanNativePath || L->isInnermost()) &&
  8067. "VPlan-native path is not enabled. Only process inner loops.");
  8068. #ifndef NDEBUG
  8069. const std::string DebugLocStr = getDebugLocString(L);
  8070. #endif /* NDEBUG */
  8071. LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
  8072. << L->getHeader()->getParent()->getName() << "\" from "
  8073. << DebugLocStr << "\n");
  8074. LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
  8075. LLVM_DEBUG(
  8076. dbgs() << "LV: Loop hints:"
  8077. << " force="
  8078. << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
  8079. ? "disabled"
  8080. : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
  8081. ? "enabled"
  8082. : "?"))
  8083. << " width=" << Hints.getWidth()
  8084. << " unroll=" << Hints.getInterleave() << "\n");
  8085. // Function containing loop
  8086. Function *F = L->getHeader()->getParent();
  8087. // Looking at the diagnostic output is the only way to determine if a loop
  8088. // was vectorized (other than looking at the IR or machine code), so it
  8089. // is important to generate an optimization remark for each loop. Most of
  8090. // these messages are generated as OptimizationRemarkAnalysis. Remarks
  8091. // generated as OptimizationRemark and OptimizationRemarkMissed are
  8092. // less verbose reporting vectorized loops and unvectorized loops that may
  8093. // benefit from vectorization, respectively.
  8094. if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
  8095. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
  8096. return false;
  8097. }
  8098. PredicatedScalarEvolution PSE(*SE, *L);
  8099. // Check if it is legal to vectorize the loop.
  8100. LoopVectorizationRequirements Requirements(*ORE);
  8101. LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
  8102. &Requirements, &Hints, DB, AC, BFI, PSI);
  8103. if (!LVL.canVectorize(EnableVPlanNativePath)) {
  8104. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
  8105. Hints.emitRemarkWithHints();
  8106. return false;
  8107. }
  8108. // Check the function attributes and profiles to find out if this function
  8109. // should be optimized for size.
  8110. ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
  8111. F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
  8112. // Entrance to the VPlan-native vectorization path. Outer loops are processed
  8113. // here. They may require CFG and instruction level transformations before
  8114. // even evaluating whether vectorization is profitable. Since we cannot modify
  8115. // the incoming IR, we need to build VPlan upfront in the vectorization
  8116. // pipeline.
  8117. if (!L->isInnermost())
  8118. return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
  8119. ORE, BFI, PSI, Hints);
  8120. assert(L->isInnermost() && "Inner loop expected.");
  8121. // Check the loop for a trip count threshold: vectorize loops with a tiny trip
  8122. // count by optimizing for size, to minimize overheads.
  8123. auto ExpectedTC = getSmallBestKnownTC(*SE, L);
  8124. if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
  8125. LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
  8126. << "This loop is worth vectorizing only if no scalar "
  8127. << "iteration overheads are incurred.");
  8128. if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
  8129. LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
  8130. else {
  8131. LLVM_DEBUG(dbgs() << "\n");
  8132. SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
  8133. }
  8134. }
  8135. // Check the function attributes to see if implicit floats are allowed.
  8136. // FIXME: This check doesn't seem possibly correct -- what if the loop is
  8137. // an integer loop and the vector instructions selected are purely integer
  8138. // vector instructions?
  8139. if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
  8140. reportVectorizationFailure(
  8141. "Can't vectorize when the NoImplicitFloat attribute is used",
  8142. "loop not vectorized due to NoImplicitFloat attribute",
  8143. "NoImplicitFloat", ORE, L);
  8144. Hints.emitRemarkWithHints();
  8145. return false;
  8146. }
  8147. // Check if the target supports potentially unsafe FP vectorization.
  8148. // FIXME: Add a check for the type of safety issue (denormal, signaling)
  8149. // for the target we're vectorizing for, to make sure none of the
  8150. // additional fp-math flags can help.
  8151. if (Hints.isPotentiallyUnsafe() &&
  8152. TTI->isFPVectorizationPotentiallyUnsafe()) {
  8153. reportVectorizationFailure(
  8154. "Potentially unsafe FP op prevents vectorization",
  8155. "loop not vectorized due to unsafe FP support.",
  8156. "UnsafeFP", ORE, L);
  8157. Hints.emitRemarkWithHints();
  8158. return false;
  8159. }
  8160. bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
  8161. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
  8162. // If an override option has been passed in for interleaved accesses, use it.
  8163. if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
  8164. UseInterleaved = EnableInterleavedMemAccesses;
  8165. // Analyze interleaved memory accesses.
  8166. if (UseInterleaved) {
  8167. IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
  8168. }
  8169. // Use the cost model.
  8170. LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
  8171. F, &Hints, IAI);
  8172. CM.collectValuesToIgnore();
  8173. // Use the planner for vectorization.
  8174. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE);
  8175. // Get user vectorization factor and interleave count.
  8176. ElementCount UserVF = Hints.getWidth();
  8177. unsigned UserIC = Hints.getInterleave();
  8178. // Plan how to best vectorize, return the best VF and its cost.
  8179. Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
  8180. VectorizationFactor VF = VectorizationFactor::Disabled();
  8181. unsigned IC = 1;
  8182. if (MaybeVF) {
  8183. VF = *MaybeVF;
  8184. // Select the interleave count.
  8185. IC = CM.selectInterleaveCount(VF.Width, VF.Cost);
  8186. }
  8187. // Identify the diagnostic messages that should be produced.
  8188. std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
  8189. bool VectorizeLoop = true, InterleaveLoop = true;
  8190. if (Requirements.doesNotMeet(F, L, Hints)) {
  8191. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
  8192. "requirements.\n");
  8193. Hints.emitRemarkWithHints();
  8194. return false;
  8195. }
  8196. if (VF.Width.isScalar()) {
  8197. LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
  8198. VecDiagMsg = std::make_pair(
  8199. "VectorizationNotBeneficial",
  8200. "the cost-model indicates that vectorization is not beneficial");
  8201. VectorizeLoop = false;
  8202. }
  8203. if (!MaybeVF && UserIC > 1) {
  8204. // Tell the user interleaving was avoided up-front, despite being explicitly
  8205. // requested.
  8206. LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
  8207. "interleaving should be avoided up front\n");
  8208. IntDiagMsg = std::make_pair(
  8209. "InterleavingAvoided",
  8210. "Ignoring UserIC, because interleaving was avoided up front");
  8211. InterleaveLoop = false;
  8212. } else if (IC == 1 && UserIC <= 1) {
  8213. // Tell the user interleaving is not beneficial.
  8214. LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
  8215. IntDiagMsg = std::make_pair(
  8216. "InterleavingNotBeneficial",
  8217. "the cost-model indicates that interleaving is not beneficial");
  8218. InterleaveLoop = false;
  8219. if (UserIC == 1) {
  8220. IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
  8221. IntDiagMsg.second +=
  8222. " and is explicitly disabled or interleave count is set to 1";
  8223. }
  8224. } else if (IC > 1 && UserIC == 1) {
  8225. // Tell the user interleaving is beneficial, but it explicitly disabled.
  8226. LLVM_DEBUG(
  8227. dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
  8228. IntDiagMsg = std::make_pair(
  8229. "InterleavingBeneficialButDisabled",
  8230. "the cost-model indicates that interleaving is beneficial "
  8231. "but is explicitly disabled or interleave count is set to 1");
  8232. InterleaveLoop = false;
  8233. }
  8234. // Override IC if user provided an interleave count.
  8235. IC = UserIC > 0 ? UserIC : IC;
  8236. // Emit diagnostic messages, if any.
  8237. const char *VAPassName = Hints.vectorizeAnalysisPassName();
  8238. if (!VectorizeLoop && !InterleaveLoop) {
  8239. // Do not vectorize or interleaving the loop.
  8240. ORE->emit([&]() {
  8241. return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
  8242. L->getStartLoc(), L->getHeader())
  8243. << VecDiagMsg.second;
  8244. });
  8245. ORE->emit([&]() {
  8246. return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
  8247. L->getStartLoc(), L->getHeader())
  8248. << IntDiagMsg.second;
  8249. });
  8250. return false;
  8251. } else if (!VectorizeLoop && InterleaveLoop) {
  8252. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  8253. ORE->emit([&]() {
  8254. return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
  8255. L->getStartLoc(), L->getHeader())
  8256. << VecDiagMsg.second;
  8257. });
  8258. } else if (VectorizeLoop && !InterleaveLoop) {
  8259. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  8260. << ") in " << DebugLocStr << '\n');
  8261. ORE->emit([&]() {
  8262. return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
  8263. L->getStartLoc(), L->getHeader())
  8264. << IntDiagMsg.second;
  8265. });
  8266. } else if (VectorizeLoop && InterleaveLoop) {
  8267. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  8268. << ") in " << DebugLocStr << '\n');
  8269. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  8270. }
  8271. LVP.setBestPlan(VF.Width, IC);
  8272. using namespace ore;
  8273. bool DisableRuntimeUnroll = false;
  8274. MDNode *OrigLoopID = L->getLoopID();
  8275. if (!VectorizeLoop) {
  8276. assert(IC > 1 && "interleave count should not be 1 or 0");
  8277. // If we decided that it is not legal to vectorize the loop, then
  8278. // interleave it.
  8279. InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL, &CM,
  8280. BFI, PSI);
  8281. LVP.executePlan(Unroller, DT);
  8282. ORE->emit([&]() {
  8283. return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
  8284. L->getHeader())
  8285. << "interleaved loop (interleaved count: "
  8286. << NV("InterleaveCount", IC) << ")";
  8287. });
  8288. } else {
  8289. // If we decided that it is *legal* to vectorize the loop, then do it.
  8290. // Consider vectorizing the epilogue too if it's profitable.
  8291. VectorizationFactor EpilogueVF =
  8292. CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
  8293. if (EpilogueVF.Width.isVector()) {
  8294. // The first pass vectorizes the main loop and creates a scalar epilogue
  8295. // to be vectorized by executing the plan (potentially with a different
  8296. // factor) again shortly afterwards.
  8297. EpilogueLoopVectorizationInfo EPI(VF.Width.getKnownMinValue(), IC,
  8298. EpilogueVF.Width.getKnownMinValue(), 1);
  8299. EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE, EPI,
  8300. &LVL, &CM, BFI, PSI);
  8301. LVP.setBestPlan(EPI.MainLoopVF, EPI.MainLoopUF);
  8302. LVP.executePlan(MainILV, DT);
  8303. ++LoopsVectorized;
  8304. simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
  8305. formLCSSARecursively(*L, *DT, LI, SE);
  8306. // Second pass vectorizes the epilogue and adjusts the control flow
  8307. // edges from the first pass.
  8308. LVP.setBestPlan(EPI.EpilogueVF, EPI.EpilogueUF);
  8309. EPI.MainLoopVF = EPI.EpilogueVF;
  8310. EPI.MainLoopUF = EPI.EpilogueUF;
  8311. EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
  8312. ORE, EPI, &LVL, &CM, BFI, PSI);
  8313. LVP.executePlan(EpilogILV, DT);
  8314. ++LoopsEpilogueVectorized;
  8315. if (!MainILV.areSafetyChecksAdded())
  8316. DisableRuntimeUnroll = true;
  8317. } else {
  8318. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
  8319. &LVL, &CM, BFI, PSI);
  8320. LVP.executePlan(LB, DT);
  8321. ++LoopsVectorized;
  8322. // Add metadata to disable runtime unrolling a scalar loop when there are
  8323. // no runtime checks about strides and memory. A scalar loop that is
  8324. // rarely used is not worth unrolling.
  8325. if (!LB.areSafetyChecksAdded())
  8326. DisableRuntimeUnroll = true;
  8327. }
  8328. // Report the vectorization decision.
  8329. ORE->emit([&]() {
  8330. return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
  8331. L->getHeader())
  8332. << "vectorized loop (vectorization width: "
  8333. << NV("VectorizationFactor", VF.Width)
  8334. << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
  8335. });
  8336. }
  8337. Optional<MDNode *> RemainderLoopID =
  8338. makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
  8339. LLVMLoopVectorizeFollowupEpilogue});
  8340. if (RemainderLoopID.hasValue()) {
  8341. L->setLoopID(RemainderLoopID.getValue());
  8342. } else {
  8343. if (DisableRuntimeUnroll)
  8344. AddRuntimeUnrollDisableMetaData(L);
  8345. // Mark the loop as already vectorized to avoid vectorizing again.
  8346. Hints.setAlreadyVectorized();
  8347. }
  8348. assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
  8349. return true;
  8350. }
  8351. LoopVectorizeResult LoopVectorizePass::runImpl(
  8352. Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
  8353. DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
  8354. DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
  8355. std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
  8356. OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
  8357. SE = &SE_;
  8358. LI = &LI_;
  8359. TTI = &TTI_;
  8360. DT = &DT_;
  8361. BFI = &BFI_;
  8362. TLI = TLI_;
  8363. AA = &AA_;
  8364. AC = &AC_;
  8365. GetLAA = &GetLAA_;
  8366. DB = &DB_;
  8367. ORE = &ORE_;
  8368. PSI = PSI_;
  8369. // Don't attempt if
  8370. // 1. the target claims to have no vector registers, and
  8371. // 2. interleaving won't help ILP.
  8372. //
  8373. // The second condition is necessary because, even if the target has no
  8374. // vector registers, loop vectorization may still enable scalar
  8375. // interleaving.
  8376. if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
  8377. TTI->getMaxInterleaveFactor(1) < 2)
  8378. return LoopVectorizeResult(false, false);
  8379. bool Changed = false, CFGChanged = false;
  8380. // The vectorizer requires loops to be in simplified form.
  8381. // Since simplification may add new inner loops, it has to run before the
  8382. // legality and profitability checks. This means running the loop vectorizer
  8383. // will simplify all loops, regardless of whether anything end up being
  8384. // vectorized.
  8385. for (auto &L : *LI)
  8386. Changed |= CFGChanged |=
  8387. simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
  8388. // Build up a worklist of inner-loops to vectorize. This is necessary as
  8389. // the act of vectorizing or partially unrolling a loop creates new loops
  8390. // and can invalidate iterators across the loops.
  8391. SmallVector<Loop *, 8> Worklist;
  8392. for (Loop *L : *LI)
  8393. collectSupportedLoops(*L, LI, ORE, Worklist);
  8394. LoopsAnalyzed += Worklist.size();
  8395. // Now walk the identified inner loops.
  8396. while (!Worklist.empty()) {
  8397. Loop *L = Worklist.pop_back_val();
  8398. // For the inner loops we actually process, form LCSSA to simplify the
  8399. // transform.
  8400. Changed |= formLCSSARecursively(*L, *DT, LI, SE);
  8401. Changed |= CFGChanged |= processLoop(L);
  8402. }
  8403. // Process each loop nest in the function.
  8404. return LoopVectorizeResult(Changed, CFGChanged);
  8405. }
  8406. PreservedAnalyses LoopVectorizePass::run(Function &F,
  8407. FunctionAnalysisManager &AM) {
  8408. auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  8409. auto &LI = AM.getResult<LoopAnalysis>(F);
  8410. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  8411. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  8412. auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
  8413. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  8414. auto &AA = AM.getResult<AAManager>(F);
  8415. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  8416. auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
  8417. auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  8418. MemorySSA *MSSA = EnableMSSALoopDependency
  8419. ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
  8420. : nullptr;
  8421. auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
  8422. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  8423. [&](Loop &L) -> const LoopAccessInfo & {
  8424. LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE,
  8425. TLI, TTI, nullptr, MSSA};
  8426. return LAM.getResult<LoopAccessAnalysis>(L, AR);
  8427. };
  8428. auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
  8429. ProfileSummaryInfo *PSI =
  8430. MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
  8431. LoopVectorizeResult Result =
  8432. runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
  8433. if (!Result.MadeAnyChange)
  8434. return PreservedAnalyses::all();
  8435. PreservedAnalyses PA;
  8436. // We currently do not preserve loopinfo/dominator analyses with outer loop
  8437. // vectorization. Until this is addressed, mark these analyses as preserved
  8438. // only for non-VPlan-native path.
  8439. // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
  8440. if (!EnableVPlanNativePath) {
  8441. PA.preserve<LoopAnalysis>();
  8442. PA.preserve<DominatorTreeAnalysis>();
  8443. }
  8444. PA.preserve<BasicAA>();
  8445. PA.preserve<GlobalsAA>();
  8446. if (!Result.MadeCFGChange)
  8447. PA.preserveSet<CFGAnalyses>();
  8448. return PA;
  8449. }