LoopVectorize.cpp 315 KB

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