LoopVectorize.cpp 305 KB

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