LoopVectorize.cpp 298 KB

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