LoopVectorize.cpp 235 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254
  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. //===----------------------------------------------------------------------===//
  30. //
  31. // The reduction-variable vectorization is based on the paper:
  32. // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
  33. //
  34. // Variable uniformity checks are inspired by:
  35. // Karrenberg, R. and Hack, S. Whole Function Vectorization.
  36. //
  37. // Other ideas/concepts are from:
  38. // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
  39. //
  40. // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
  41. // Vectorizing Compilers.
  42. //
  43. //===----------------------------------------------------------------------===//
  44. #include "llvm/Transforms/Vectorize.h"
  45. #include "llvm/ADT/DenseMap.h"
  46. #include "llvm/ADT/EquivalenceClasses.h"
  47. #include "llvm/ADT/Hashing.h"
  48. #include "llvm/ADT/MapVector.h"
  49. #include "llvm/ADT/SetVector.h"
  50. #include "llvm/ADT/SmallPtrSet.h"
  51. #include "llvm/ADT/SmallSet.h"
  52. #include "llvm/ADT/SmallVector.h"
  53. #include "llvm/ADT/Statistic.h"
  54. #include "llvm/ADT/StringExtras.h"
  55. #include "llvm/Analysis/AliasAnalysis.h"
  56. #include "llvm/Analysis/AliasSetTracker.h"
  57. #include "llvm/Analysis/AssumptionTracker.h"
  58. #include "llvm/Analysis/BlockFrequencyInfo.h"
  59. #include "llvm/Analysis/CodeMetrics.h"
  60. #include "llvm/Analysis/LoopInfo.h"
  61. #include "llvm/Analysis/LoopIterator.h"
  62. #include "llvm/Analysis/LoopPass.h"
  63. #include "llvm/Analysis/ScalarEvolution.h"
  64. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  65. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  66. #include "llvm/Analysis/TargetTransformInfo.h"
  67. #include "llvm/Analysis/ValueTracking.h"
  68. #include "llvm/IR/Constants.h"
  69. #include "llvm/IR/DataLayout.h"
  70. #include "llvm/IR/DebugInfo.h"
  71. #include "llvm/IR/DerivedTypes.h"
  72. #include "llvm/IR/DiagnosticInfo.h"
  73. #include "llvm/IR/Dominators.h"
  74. #include "llvm/IR/Function.h"
  75. #include "llvm/IR/IRBuilder.h"
  76. #include "llvm/IR/Instructions.h"
  77. #include "llvm/IR/IntrinsicInst.h"
  78. #include "llvm/IR/LLVMContext.h"
  79. #include "llvm/IR/Module.h"
  80. #include "llvm/IR/PatternMatch.h"
  81. #include "llvm/IR/Type.h"
  82. #include "llvm/IR/Value.h"
  83. #include "llvm/IR/ValueHandle.h"
  84. #include "llvm/IR/Verifier.h"
  85. #include "llvm/Pass.h"
  86. #include "llvm/Support/BranchProbability.h"
  87. #include "llvm/Support/CommandLine.h"
  88. #include "llvm/Support/Debug.h"
  89. #include "llvm/Support/raw_ostream.h"
  90. #include "llvm/Transforms/Scalar.h"
  91. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  92. #include "llvm/Transforms/Utils/Local.h"
  93. #include "llvm/Transforms/Utils/VectorUtils.h"
  94. #include <algorithm>
  95. #include <map>
  96. #include <tuple>
  97. using namespace llvm;
  98. using namespace llvm::PatternMatch;
  99. #define LV_NAME "loop-vectorize"
  100. #define DEBUG_TYPE LV_NAME
  101. STATISTIC(LoopsVectorized, "Number of loops vectorized");
  102. STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
  103. static cl::opt<unsigned>
  104. VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
  105. cl::desc("Sets the SIMD width. Zero is autoselect."));
  106. static cl::opt<unsigned>
  107. VectorizationInterleave("force-vector-interleave", cl::init(0), cl::Hidden,
  108. cl::desc("Sets the vectorization interleave count. "
  109. "Zero is autoselect."));
  110. static cl::opt<bool>
  111. EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
  112. cl::desc("Enable if-conversion during vectorization."));
  113. /// We don't vectorize loops with a known constant trip count below this number.
  114. static cl::opt<unsigned>
  115. TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
  116. cl::Hidden,
  117. cl::desc("Don't vectorize loops with a constant "
  118. "trip count that is smaller than this "
  119. "value."));
  120. /// This enables versioning on the strides of symbolically striding memory
  121. /// accesses in code like the following.
  122. /// for (i = 0; i < N; ++i)
  123. /// A[i * Stride1] += B[i * Stride2] ...
  124. ///
  125. /// Will be roughly translated to
  126. /// if (Stride1 == 1 && Stride2 == 1) {
  127. /// for (i = 0; i < N; i+=4)
  128. /// A[i:i+3] += ...
  129. /// } else
  130. /// ...
  131. static cl::opt<bool> EnableMemAccessVersioning(
  132. "enable-mem-access-versioning", cl::init(true), cl::Hidden,
  133. cl::desc("Enable symblic stride memory access versioning"));
  134. /// We don't unroll loops with a known constant trip count below this number.
  135. static const unsigned TinyTripCountUnrollThreshold = 128;
  136. /// When performing memory disambiguation checks at runtime do not make more
  137. /// than this number of comparisons.
  138. static const unsigned RuntimeMemoryCheckThreshold = 8;
  139. /// Maximum simd width.
  140. static const unsigned MaxVectorWidth = 64;
  141. static cl::opt<unsigned> ForceTargetNumScalarRegs(
  142. "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
  143. cl::desc("A flag that overrides the target's number of scalar registers."));
  144. static cl::opt<unsigned> ForceTargetNumVectorRegs(
  145. "force-target-num-vector-regs", cl::init(0), cl::Hidden,
  146. cl::desc("A flag that overrides the target's number of vector registers."));
  147. /// Maximum vectorization interleave count.
  148. static const unsigned MaxInterleaveFactor = 16;
  149. static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
  150. "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
  151. cl::desc("A flag that overrides the target's max interleave factor for "
  152. "scalar loops."));
  153. static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
  154. "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
  155. cl::desc("A flag that overrides the target's max interleave factor for "
  156. "vectorized loops."));
  157. static cl::opt<unsigned> ForceTargetInstructionCost(
  158. "force-target-instruction-cost", cl::init(0), cl::Hidden,
  159. cl::desc("A flag that overrides the target's expected cost for "
  160. "an instruction to a single constant value. Mostly "
  161. "useful for getting consistent testing."));
  162. static cl::opt<unsigned> SmallLoopCost(
  163. "small-loop-cost", cl::init(20), cl::Hidden,
  164. cl::desc("The cost of a loop that is considered 'small' by the unroller."));
  165. static cl::opt<bool> LoopVectorizeWithBlockFrequency(
  166. "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
  167. cl::desc("Enable the use of the block frequency analysis to access PGO "
  168. "heuristics minimizing code growth in cold regions and being more "
  169. "aggressive in hot regions."));
  170. // Runtime unroll loops for load/store throughput.
  171. static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
  172. "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
  173. cl::desc("Enable runtime unrolling until load/store ports are saturated"));
  174. /// The number of stores in a loop that are allowed to need predication.
  175. static cl::opt<unsigned> NumberOfStoresToPredicate(
  176. "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
  177. cl::desc("Max number of stores to be predicated behind an if."));
  178. static cl::opt<bool> EnableIndVarRegisterHeur(
  179. "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
  180. cl::desc("Count the induction variable only once when unrolling"));
  181. static cl::opt<bool> EnableCondStoresVectorization(
  182. "enable-cond-stores-vec", cl::init(false), cl::Hidden,
  183. cl::desc("Enable if predication of stores during vectorization."));
  184. static cl::opt<unsigned> MaxNestedScalarReductionUF(
  185. "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
  186. cl::desc("The maximum unroll factor to use when unrolling a scalar "
  187. "reduction in a nested loop."));
  188. namespace {
  189. // Forward declarations.
  190. class LoopVectorizationLegality;
  191. class LoopVectorizationCostModel;
  192. class LoopVectorizeHints;
  193. /// Optimization analysis message produced during vectorization. Messages inform
  194. /// the user why vectorization did not occur.
  195. class Report {
  196. std::string Message;
  197. raw_string_ostream Out;
  198. Instruction *Instr;
  199. public:
  200. Report(Instruction *I = nullptr) : Out(Message), Instr(I) {
  201. Out << "loop not vectorized: ";
  202. }
  203. template <typename A> Report &operator<<(const A &Value) {
  204. Out << Value;
  205. return *this;
  206. }
  207. Instruction *getInstr() { return Instr; }
  208. std::string &str() { return Out.str(); }
  209. operator Twine() { return Out.str(); }
  210. };
  211. /// InnerLoopVectorizer vectorizes loops which contain only one basic
  212. /// block to a specified vectorization factor (VF).
  213. /// This class performs the widening of scalars into vectors, or multiple
  214. /// scalars. This class also implements the following features:
  215. /// * It inserts an epilogue loop for handling loops that don't have iteration
  216. /// counts that are known to be a multiple of the vectorization factor.
  217. /// * It handles the code generation for reduction variables.
  218. /// * Scalarization (implementation using scalars) of un-vectorizable
  219. /// instructions.
  220. /// InnerLoopVectorizer does not perform any vectorization-legality
  221. /// checks, and relies on the caller to check for the different legality
  222. /// aspects. The InnerLoopVectorizer relies on the
  223. /// LoopVectorizationLegality class to provide information about the induction
  224. /// and reduction variables that were found to a given vectorization factor.
  225. class InnerLoopVectorizer {
  226. public:
  227. InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
  228. DominatorTree *DT, const DataLayout *DL,
  229. const TargetLibraryInfo *TLI, unsigned VecWidth,
  230. unsigned UnrollFactor)
  231. : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
  232. VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
  233. Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
  234. Legal(nullptr) {}
  235. // Perform the actual loop widening (vectorization).
  236. void vectorize(LoopVectorizationLegality *L) {
  237. Legal = L;
  238. // Create a new empty loop. Unlink the old loop and connect the new one.
  239. createEmptyLoop();
  240. // Widen each instruction in the old loop to a new one in the new loop.
  241. // Use the Legality module to find the induction and reduction variables.
  242. vectorizeLoop();
  243. // Register the new loop and update the analysis passes.
  244. updateAnalysis();
  245. }
  246. virtual ~InnerLoopVectorizer() {}
  247. protected:
  248. /// A small list of PHINodes.
  249. typedef SmallVector<PHINode*, 4> PhiVector;
  250. /// When we unroll loops we have multiple vector values for each scalar.
  251. /// This data structure holds the unrolled and vectorized values that
  252. /// originated from one scalar instruction.
  253. typedef SmallVector<Value*, 2> VectorParts;
  254. // When we if-convert we need create edge masks. We have to cache values so
  255. // that we don't end up with exponential recursion/IR.
  256. typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
  257. VectorParts> EdgeMaskCache;
  258. /// \brief Add code that checks at runtime if the accessed arrays overlap.
  259. ///
  260. /// Returns a pair of instructions where the first element is the first
  261. /// instruction generated in possibly a sequence of instructions and the
  262. /// second value is the final comparator value or NULL if no check is needed.
  263. std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
  264. /// \brief Add checks for strides that where assumed to be 1.
  265. ///
  266. /// Returns the last check instruction and the first check instruction in the
  267. /// pair as (first, last).
  268. std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
  269. /// Create an empty loop, based on the loop ranges of the old loop.
  270. void createEmptyLoop();
  271. /// Copy and widen the instructions from the old loop.
  272. virtual void vectorizeLoop();
  273. /// \brief The Loop exit block may have single value PHI nodes where the
  274. /// incoming value is 'Undef'. While vectorizing we only handled real values
  275. /// that were defined inside the loop. Here we fix the 'undef case'.
  276. /// See PR14725.
  277. void fixLCSSAPHIs();
  278. /// A helper function that computes the predicate of the block BB, assuming
  279. /// that the header block of the loop is set to True. It returns the *entry*
  280. /// mask for the block BB.
  281. VectorParts createBlockInMask(BasicBlock *BB);
  282. /// A helper function that computes the predicate of the edge between SRC
  283. /// and DST.
  284. VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
  285. /// A helper function to vectorize a single BB within the innermost loop.
  286. void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
  287. /// Vectorize a single PHINode in a block. This method handles the induction
  288. /// variable canonicalization. It supports both VF = 1 for unrolled loops and
  289. /// arbitrary length vectors.
  290. void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
  291. unsigned UF, unsigned VF, PhiVector *PV);
  292. /// Insert the new loop to the loop hierarchy and pass manager
  293. /// and update the analysis passes.
  294. void updateAnalysis();
  295. /// This instruction is un-vectorizable. Implement it as a sequence
  296. /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
  297. /// scalarized instruction behind an if block predicated on the control
  298. /// dependence of the instruction.
  299. virtual void scalarizeInstruction(Instruction *Instr,
  300. bool IfPredicateStore=false);
  301. /// Vectorize Load and Store instructions,
  302. virtual void vectorizeMemoryInstruction(Instruction *Instr);
  303. /// Create a broadcast instruction. This method generates a broadcast
  304. /// instruction (shuffle) for loop invariant values and for the induction
  305. /// value. If this is the induction variable then we extend it to N, N+1, ...
  306. /// this is needed because each iteration in the loop corresponds to a SIMD
  307. /// element.
  308. virtual Value *getBroadcastInstrs(Value *V);
  309. /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
  310. /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
  311. /// The sequence starts at StartIndex.
  312. virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
  313. /// When we go over instructions in the basic block we rely on previous
  314. /// values within the current basic block or on loop invariant values.
  315. /// When we widen (vectorize) values we place them in the map. If the values
  316. /// are not within the map, they have to be loop invariant, so we simply
  317. /// broadcast them into a vector.
  318. VectorParts &getVectorValue(Value *V);
  319. /// Generate a shuffle sequence that will reverse the vector Vec.
  320. virtual Value *reverseVector(Value *Vec);
  321. /// This is a helper class that holds the vectorizer state. It maps scalar
  322. /// instructions to vector instructions. When the code is 'unrolled' then
  323. /// then a single scalar value is mapped to multiple vector parts. The parts
  324. /// are stored in the VectorPart type.
  325. struct ValueMap {
  326. /// C'tor. UnrollFactor controls the number of vectors ('parts') that
  327. /// are mapped.
  328. ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
  329. /// \return True if 'Key' is saved in the Value Map.
  330. bool has(Value *Key) const { return MapStorage.count(Key); }
  331. /// Initializes a new entry in the map. Sets all of the vector parts to the
  332. /// save value in 'Val'.
  333. /// \return A reference to a vector with splat values.
  334. VectorParts &splat(Value *Key, Value *Val) {
  335. VectorParts &Entry = MapStorage[Key];
  336. Entry.assign(UF, Val);
  337. return Entry;
  338. }
  339. ///\return A reference to the value that is stored at 'Key'.
  340. VectorParts &get(Value *Key) {
  341. VectorParts &Entry = MapStorage[Key];
  342. if (Entry.empty())
  343. Entry.resize(UF);
  344. assert(Entry.size() == UF);
  345. return Entry;
  346. }
  347. private:
  348. /// The unroll factor. Each entry in the map stores this number of vector
  349. /// elements.
  350. unsigned UF;
  351. /// Map storage. We use std::map and not DenseMap because insertions to a
  352. /// dense map invalidates its iterators.
  353. std::map<Value *, VectorParts> MapStorage;
  354. };
  355. /// The original loop.
  356. Loop *OrigLoop;
  357. /// Scev analysis to use.
  358. ScalarEvolution *SE;
  359. /// Loop Info.
  360. LoopInfo *LI;
  361. /// Dominator Tree.
  362. DominatorTree *DT;
  363. /// Alias Analysis.
  364. AliasAnalysis *AA;
  365. /// Data Layout.
  366. const DataLayout *DL;
  367. /// Target Library Info.
  368. const TargetLibraryInfo *TLI;
  369. /// The vectorization SIMD factor to use. Each vector will have this many
  370. /// vector elements.
  371. unsigned VF;
  372. protected:
  373. /// The vectorization unroll factor to use. Each scalar is vectorized to this
  374. /// many different vector instructions.
  375. unsigned UF;
  376. /// The builder that we use
  377. IRBuilder<> Builder;
  378. // --- Vectorization state ---
  379. /// The vector-loop preheader.
  380. BasicBlock *LoopVectorPreHeader;
  381. /// The scalar-loop preheader.
  382. BasicBlock *LoopScalarPreHeader;
  383. /// Middle Block between the vector and the scalar.
  384. BasicBlock *LoopMiddleBlock;
  385. ///The ExitBlock of the scalar loop.
  386. BasicBlock *LoopExitBlock;
  387. ///The vector loop body.
  388. SmallVector<BasicBlock *, 4> LoopVectorBody;
  389. ///The scalar loop body.
  390. BasicBlock *LoopScalarBody;
  391. /// A list of all bypass blocks. The first block is the entry of the loop.
  392. SmallVector<BasicBlock *, 4> LoopBypassBlocks;
  393. /// The new Induction variable which was added to the new block.
  394. PHINode *Induction;
  395. /// The induction variable of the old basic block.
  396. PHINode *OldInduction;
  397. /// Holds the extended (to the widest induction type) start index.
  398. Value *ExtendedIdx;
  399. /// Maps scalars to widened vectors.
  400. ValueMap WidenMap;
  401. EdgeMaskCache MaskCache;
  402. LoopVectorizationLegality *Legal;
  403. };
  404. class InnerLoopUnroller : public InnerLoopVectorizer {
  405. public:
  406. InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
  407. DominatorTree *DT, const DataLayout *DL,
  408. const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
  409. InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
  410. private:
  411. void scalarizeInstruction(Instruction *Instr,
  412. bool IfPredicateStore = false) override;
  413. void vectorizeMemoryInstruction(Instruction *Instr) override;
  414. Value *getBroadcastInstrs(Value *V) override;
  415. Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
  416. Value *reverseVector(Value *Vec) override;
  417. };
  418. /// \brief Look for a meaningful debug location on the instruction or it's
  419. /// operands.
  420. static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
  421. if (!I)
  422. return I;
  423. DebugLoc Empty;
  424. if (I->getDebugLoc() != Empty)
  425. return I;
  426. for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
  427. if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
  428. if (OpInst->getDebugLoc() != Empty)
  429. return OpInst;
  430. }
  431. return I;
  432. }
  433. /// \brief Set the debug location in the builder using the debug location in the
  434. /// instruction.
  435. static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
  436. if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
  437. B.SetCurrentDebugLocation(Inst->getDebugLoc());
  438. else
  439. B.SetCurrentDebugLocation(DebugLoc());
  440. }
  441. #ifndef NDEBUG
  442. /// \return string containing a file name and a line # for the given loop.
  443. static std::string getDebugLocString(const Loop *L) {
  444. std::string Result;
  445. if (L) {
  446. raw_string_ostream OS(Result);
  447. const DebugLoc LoopDbgLoc = L->getStartLoc();
  448. if (!LoopDbgLoc.isUnknown())
  449. LoopDbgLoc.print(L->getHeader()->getContext(), OS);
  450. else
  451. // Just print the module name.
  452. OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
  453. OS.flush();
  454. }
  455. return Result;
  456. }
  457. #endif
  458. /// \brief Propagate known metadata from one instruction to another.
  459. static void propagateMetadata(Instruction *To, const Instruction *From) {
  460. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  461. From->getAllMetadataOtherThanDebugLoc(Metadata);
  462. for (auto M : Metadata) {
  463. unsigned Kind = M.first;
  464. // These are safe to transfer (this is safe for TBAA, even when we
  465. // if-convert, because should that metadata have had a control dependency
  466. // on the condition, and thus actually aliased with some other
  467. // non-speculated memory access when the condition was false, this would be
  468. // caught by the runtime overlap checks).
  469. if (Kind != LLVMContext::MD_tbaa &&
  470. Kind != LLVMContext::MD_alias_scope &&
  471. Kind != LLVMContext::MD_noalias &&
  472. Kind != LLVMContext::MD_fpmath)
  473. continue;
  474. To->setMetadata(Kind, M.second);
  475. }
  476. }
  477. /// \brief Propagate known metadata from one instruction to a vector of others.
  478. static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
  479. for (Value *V : To)
  480. if (Instruction *I = dyn_cast<Instruction>(V))
  481. propagateMetadata(I, From);
  482. }
  483. /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
  484. /// to what vectorization factor.
  485. /// This class does not look at the profitability of vectorization, only the
  486. /// legality. This class has two main kinds of checks:
  487. /// * Memory checks - The code in canVectorizeMemory checks if vectorization
  488. /// will change the order of memory accesses in a way that will change the
  489. /// correctness of the program.
  490. /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
  491. /// checks for a number of different conditions, such as the availability of a
  492. /// single induction variable, that all types are supported and vectorize-able,
  493. /// etc. This code reflects the capabilities of InnerLoopVectorizer.
  494. /// This class is also used by InnerLoopVectorizer for identifying
  495. /// induction variable and the different reduction variables.
  496. class LoopVectorizationLegality {
  497. public:
  498. unsigned NumLoads;
  499. unsigned NumStores;
  500. unsigned NumPredStores;
  501. LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
  502. DominatorTree *DT, TargetLibraryInfo *TLI,
  503. AliasAnalysis *AA, Function *F)
  504. : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
  505. DT(DT), TLI(TLI), AA(AA), TheFunction(F), Induction(nullptr),
  506. WidestIndTy(nullptr), HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {
  507. }
  508. /// This enum represents the kinds of reductions that we support.
  509. enum ReductionKind {
  510. RK_NoReduction, ///< Not a reduction.
  511. RK_IntegerAdd, ///< Sum of integers.
  512. RK_IntegerMult, ///< Product of integers.
  513. RK_IntegerOr, ///< Bitwise or logical OR of numbers.
  514. RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
  515. RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
  516. RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
  517. RK_FloatAdd, ///< Sum of floats.
  518. RK_FloatMult, ///< Product of floats.
  519. RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
  520. };
  521. /// This enum represents the kinds of inductions that we support.
  522. enum InductionKind {
  523. IK_NoInduction, ///< Not an induction variable.
  524. IK_IntInduction, ///< Integer induction variable. Step = 1.
  525. IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
  526. IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
  527. IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
  528. };
  529. // This enum represents the kind of minmax reduction.
  530. enum MinMaxReductionKind {
  531. MRK_Invalid,
  532. MRK_UIntMin,
  533. MRK_UIntMax,
  534. MRK_SIntMin,
  535. MRK_SIntMax,
  536. MRK_FloatMin,
  537. MRK_FloatMax
  538. };
  539. /// This struct holds information about reduction variables.
  540. struct ReductionDescriptor {
  541. ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
  542. Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
  543. ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
  544. MinMaxReductionKind MK)
  545. : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
  546. // The starting value of the reduction.
  547. // It does not have to be zero!
  548. TrackingVH<Value> StartValue;
  549. // The instruction who's value is used outside the loop.
  550. Instruction *LoopExitInstr;
  551. // The kind of the reduction.
  552. ReductionKind Kind;
  553. // If this a min/max reduction the kind of reduction.
  554. MinMaxReductionKind MinMaxKind;
  555. };
  556. /// This POD struct holds information about a potential reduction operation.
  557. struct ReductionInstDesc {
  558. ReductionInstDesc(bool IsRedux, Instruction *I) :
  559. IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
  560. ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
  561. IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
  562. // Is this instruction a reduction candidate.
  563. bool IsReduction;
  564. // The last instruction in a min/max pattern (select of the select(icmp())
  565. // pattern), or the current reduction instruction otherwise.
  566. Instruction *PatternLastInst;
  567. // If this is a min/max pattern the comparison predicate.
  568. MinMaxReductionKind MinMaxKind;
  569. };
  570. /// This struct holds information about the memory runtime legality
  571. /// check that a group of pointers do not overlap.
  572. struct RuntimePointerCheck {
  573. RuntimePointerCheck() : Need(false) {}
  574. /// Reset the state of the pointer runtime information.
  575. void reset() {
  576. Need = false;
  577. Pointers.clear();
  578. Starts.clear();
  579. Ends.clear();
  580. IsWritePtr.clear();
  581. DependencySetId.clear();
  582. AliasSetId.clear();
  583. }
  584. /// Insert a pointer and calculate the start and end SCEVs.
  585. void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
  586. unsigned DepSetId, unsigned ASId, ValueToValueMap &Strides);
  587. /// This flag indicates if we need to add the runtime check.
  588. bool Need;
  589. /// Holds the pointers that we need to check.
  590. SmallVector<TrackingVH<Value>, 2> Pointers;
  591. /// Holds the pointer value at the beginning of the loop.
  592. SmallVector<const SCEV*, 2> Starts;
  593. /// Holds the pointer value at the end of the loop.
  594. SmallVector<const SCEV*, 2> Ends;
  595. /// Holds the information if this pointer is used for writing to memory.
  596. SmallVector<bool, 2> IsWritePtr;
  597. /// Holds the id of the set of pointers that could be dependent because of a
  598. /// shared underlying object.
  599. SmallVector<unsigned, 2> DependencySetId;
  600. /// Holds the id of the disjoint alias set to which this pointer belongs.
  601. SmallVector<unsigned, 2> AliasSetId;
  602. };
  603. /// A struct for saving information about induction variables.
  604. struct InductionInfo {
  605. InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
  606. InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
  607. /// Start value.
  608. TrackingVH<Value> StartValue;
  609. /// Induction kind.
  610. InductionKind IK;
  611. };
  612. /// ReductionList contains the reduction descriptors for all
  613. /// of the reductions that were found in the loop.
  614. typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
  615. /// InductionList saves induction variables and maps them to the
  616. /// induction descriptor.
  617. typedef MapVector<PHINode*, InductionInfo> InductionList;
  618. /// Returns true if it is legal to vectorize this loop.
  619. /// This does not mean that it is profitable to vectorize this
  620. /// loop, only that it is legal to do so.
  621. bool canVectorize();
  622. /// Returns the Induction variable.
  623. PHINode *getInduction() { return Induction; }
  624. /// Returns the reduction variables found in the loop.
  625. ReductionList *getReductionVars() { return &Reductions; }
  626. /// Returns the induction variables found in the loop.
  627. InductionList *getInductionVars() { return &Inductions; }
  628. /// Returns the widest induction type.
  629. Type *getWidestInductionType() { return WidestIndTy; }
  630. /// Returns True if V is an induction variable in this loop.
  631. bool isInductionVariable(const Value *V);
  632. /// Return true if the block BB needs to be predicated in order for the loop
  633. /// to be vectorized.
  634. bool blockNeedsPredication(BasicBlock *BB);
  635. /// Check if this pointer is consecutive when vectorizing. This happens
  636. /// when the last index of the GEP is the induction variable, or that the
  637. /// pointer itself is an induction variable.
  638. /// This check allows us to vectorize A[idx] into a wide load/store.
  639. /// Returns:
  640. /// 0 - Stride is unknown or non-consecutive.
  641. /// 1 - Address is consecutive.
  642. /// -1 - Address is consecutive, and decreasing.
  643. int isConsecutivePtr(Value *Ptr);
  644. /// Returns true if the value V is uniform within the loop.
  645. bool isUniform(Value *V);
  646. /// Returns true if this instruction will remain scalar after vectorization.
  647. bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
  648. /// Returns the information that we collected about runtime memory check.
  649. RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
  650. /// This function returns the identity element (or neutral element) for
  651. /// the operation K.
  652. static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
  653. unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
  654. bool hasStride(Value *V) { return StrideSet.count(V); }
  655. bool mustCheckStrides() { return !StrideSet.empty(); }
  656. SmallPtrSet<Value *, 8>::iterator strides_begin() {
  657. return StrideSet.begin();
  658. }
  659. SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
  660. private:
  661. /// Check if a single basic block loop is vectorizable.
  662. /// At this point we know that this is a loop with a constant trip count
  663. /// and we only need to check individual instructions.
  664. bool canVectorizeInstrs();
  665. /// When we vectorize loops we may change the order in which
  666. /// we read and write from memory. This method checks if it is
  667. /// legal to vectorize the code, considering only memory constrains.
  668. /// Returns true if the loop is vectorizable
  669. bool canVectorizeMemory();
  670. /// Return true if we can vectorize this loop using the IF-conversion
  671. /// transformation.
  672. bool canVectorizeWithIfConvert();
  673. /// Collect the variables that need to stay uniform after vectorization.
  674. void collectLoopUniforms();
  675. /// Return true if all of the instructions in the block can be speculatively
  676. /// executed. \p SafePtrs is a list of addresses that are known to be legal
  677. /// and we know that we can read from them without segfault.
  678. bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
  679. /// Returns True, if 'Phi' is the kind of reduction variable for type
  680. /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
  681. bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
  682. /// Returns a struct describing if the instruction 'I' can be a reduction
  683. /// variable of type 'Kind'. If the reduction is a min/max pattern of
  684. /// select(icmp()) this function advances the instruction pointer 'I' from the
  685. /// compare instruction to the select instruction and stores this pointer in
  686. /// 'PatternLastInst' member of the returned struct.
  687. ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
  688. ReductionInstDesc &Desc);
  689. /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
  690. /// pattern corresponding to a min(X, Y) or max(X, Y).
  691. static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
  692. ReductionInstDesc &Prev);
  693. /// Returns the induction kind of Phi. This function may return NoInduction
  694. /// if the PHI is not an induction variable.
  695. InductionKind isInductionVariable(PHINode *Phi);
  696. /// \brief Collect memory access with loop invariant strides.
  697. ///
  698. /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
  699. /// invariant.
  700. void collectStridedAcccess(Value *LoadOrStoreInst);
  701. /// Report an analysis message to assist the user in diagnosing loops that are
  702. /// not vectorized.
  703. void emitAnalysis(Report &Message) {
  704. DebugLoc DL = TheLoop->getStartLoc();
  705. if (Instruction *I = Message.getInstr())
  706. DL = I->getDebugLoc();
  707. emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
  708. *TheFunction, DL, Message.str());
  709. }
  710. /// The loop that we evaluate.
  711. Loop *TheLoop;
  712. /// Scev analysis.
  713. ScalarEvolution *SE;
  714. /// DataLayout analysis.
  715. const DataLayout *DL;
  716. /// Dominators.
  717. DominatorTree *DT;
  718. /// Target Library Info.
  719. TargetLibraryInfo *TLI;
  720. /// Alias analysis.
  721. AliasAnalysis *AA;
  722. /// Parent function
  723. Function *TheFunction;
  724. // --- vectorization state --- //
  725. /// Holds the integer induction variable. This is the counter of the
  726. /// loop.
  727. PHINode *Induction;
  728. /// Holds the reduction variables.
  729. ReductionList Reductions;
  730. /// Holds all of the induction variables that we found in the loop.
  731. /// Notice that inductions don't need to start at zero and that induction
  732. /// variables can be pointers.
  733. InductionList Inductions;
  734. /// Holds the widest induction type encountered.
  735. Type *WidestIndTy;
  736. /// Allowed outside users. This holds the reduction
  737. /// vars which can be accessed from outside the loop.
  738. SmallPtrSet<Value*, 4> AllowedExit;
  739. /// This set holds the variables which are known to be uniform after
  740. /// vectorization.
  741. SmallPtrSet<Instruction*, 4> Uniforms;
  742. /// We need to check that all of the pointers in this list are disjoint
  743. /// at runtime.
  744. RuntimePointerCheck PtrRtCheck;
  745. /// Can we assume the absence of NaNs.
  746. bool HasFunNoNaNAttr;
  747. unsigned MaxSafeDepDistBytes;
  748. ValueToValueMap Strides;
  749. SmallPtrSet<Value *, 8> StrideSet;
  750. };
  751. /// LoopVectorizationCostModel - estimates the expected speedups due to
  752. /// vectorization.
  753. /// In many cases vectorization is not profitable. This can happen because of
  754. /// a number of reasons. In this class we mainly attempt to predict the
  755. /// expected speedup/slowdowns due to the supported instruction set. We use the
  756. /// TargetTransformInfo to query the different backends for the cost of
  757. /// different operations.
  758. class LoopVectorizationCostModel {
  759. public:
  760. LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
  761. LoopVectorizationLegality *Legal,
  762. const TargetTransformInfo &TTI,
  763. const DataLayout *DL, const TargetLibraryInfo *TLI,
  764. AssumptionTracker *AT, const Function *F,
  765. const LoopVectorizeHints *Hints)
  766. : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI),
  767. TheFunction(F), Hints(Hints) {
  768. CodeMetrics::collectEphemeralValues(L, AT, EphValues);
  769. }
  770. /// Information about vectorization costs
  771. struct VectorizationFactor {
  772. unsigned Width; // Vector width with best cost
  773. unsigned Cost; // Cost of the loop with that width
  774. };
  775. /// \return The most profitable vectorization factor and the cost of that VF.
  776. /// This method checks every power of two up to VF. If UserVF is not ZERO
  777. /// then this vectorization factor will be selected if vectorization is
  778. /// possible.
  779. VectorizationFactor selectVectorizationFactor(bool OptForSize);
  780. /// \return The size (in bits) of the widest type in the code that
  781. /// needs to be vectorized. We ignore values that remain scalar such as
  782. /// 64 bit loop indices.
  783. unsigned getWidestType();
  784. /// \return The most profitable unroll factor.
  785. /// If UserUF is non-zero then this method finds the best unroll-factor
  786. /// based on register pressure and other parameters.
  787. /// VF and LoopCost are the selected vectorization factor and the cost of the
  788. /// selected VF.
  789. unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
  790. /// \brief A struct that represents some properties of the register usage
  791. /// of a loop.
  792. struct RegisterUsage {
  793. /// Holds the number of loop invariant values that are used in the loop.
  794. unsigned LoopInvariantRegs;
  795. /// Holds the maximum number of concurrent live intervals in the loop.
  796. unsigned MaxLocalUsers;
  797. /// Holds the number of instructions in the loop.
  798. unsigned NumInstructions;
  799. };
  800. /// \return information about the register usage of the loop.
  801. RegisterUsage calculateRegisterUsage();
  802. private:
  803. /// Returns the expected execution cost. The unit of the cost does
  804. /// not matter because we use the 'cost' units to compare different
  805. /// vector widths. The cost that is returned is *not* normalized by
  806. /// the factor width.
  807. unsigned expectedCost(unsigned VF);
  808. /// Returns the execution time cost of an instruction for a given vector
  809. /// width. Vector width of one means scalar.
  810. unsigned getInstructionCost(Instruction *I, unsigned VF);
  811. /// A helper function for converting Scalar types to vector types.
  812. /// If the incoming type is void, we return void. If the VF is 1, we return
  813. /// the scalar type.
  814. static Type* ToVectorTy(Type *Scalar, unsigned VF);
  815. /// Returns whether the instruction is a load or store and will be a emitted
  816. /// as a vector operation.
  817. bool isConsecutiveLoadOrStore(Instruction *I);
  818. /// Report an analysis message to assist the user in diagnosing loops that are
  819. /// not vectorized.
  820. void emitAnalysis(Report &Message) {
  821. DebugLoc DL = TheLoop->getStartLoc();
  822. if (Instruction *I = Message.getInstr())
  823. DL = I->getDebugLoc();
  824. emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
  825. *TheFunction, DL, Message.str());
  826. }
  827. /// Values used only by @llvm.assume calls.
  828. SmallPtrSet<const Value *, 32> EphValues;
  829. /// The loop that we evaluate.
  830. Loop *TheLoop;
  831. /// Scev analysis.
  832. ScalarEvolution *SE;
  833. /// Loop Info analysis.
  834. LoopInfo *LI;
  835. /// Vectorization legality.
  836. LoopVectorizationLegality *Legal;
  837. /// Vector target information.
  838. const TargetTransformInfo &TTI;
  839. /// Target data layout information.
  840. const DataLayout *DL;
  841. /// Target Library Info.
  842. const TargetLibraryInfo *TLI;
  843. const Function *TheFunction;
  844. // Loop Vectorize Hint.
  845. const LoopVectorizeHints *Hints;
  846. };
  847. /// Utility class for getting and setting loop vectorizer hints in the form
  848. /// of loop metadata.
  849. /// This class keeps a number of loop annotations locally (as member variables)
  850. /// and can, upon request, write them back as metadata on the loop. It will
  851. /// initially scan the loop for existing metadata, and will update the local
  852. /// values based on information in the loop.
  853. /// We cannot write all values to metadata, as the mere presence of some info,
  854. /// for example 'force', means a decision has been made. So, we need to be
  855. /// careful NOT to add them if the user hasn't specifically asked so.
  856. class LoopVectorizeHints {
  857. enum HintKind {
  858. HK_WIDTH,
  859. HK_UNROLL,
  860. HK_FORCE
  861. };
  862. /// Hint - associates name and validation with the hint value.
  863. struct Hint {
  864. const char * Name;
  865. unsigned Value; // This may have to change for non-numeric values.
  866. HintKind Kind;
  867. Hint(const char * Name, unsigned Value, HintKind Kind)
  868. : Name(Name), Value(Value), Kind(Kind) { }
  869. bool validate(unsigned Val) {
  870. switch (Kind) {
  871. case HK_WIDTH:
  872. return isPowerOf2_32(Val) && Val <= MaxVectorWidth;
  873. case HK_UNROLL:
  874. return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
  875. case HK_FORCE:
  876. return (Val <= 1);
  877. }
  878. return false;
  879. }
  880. };
  881. /// Vectorization width.
  882. Hint Width;
  883. /// Vectorization interleave factor.
  884. Hint Interleave;
  885. /// Vectorization forced
  886. Hint Force;
  887. /// Return the loop metadata prefix.
  888. static StringRef Prefix() { return "llvm.loop."; }
  889. public:
  890. enum ForceKind {
  891. FK_Undefined = -1, ///< Not selected.
  892. FK_Disabled = 0, ///< Forcing disabled.
  893. FK_Enabled = 1, ///< Forcing enabled.
  894. };
  895. LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
  896. : Width("vectorize.width", VectorizationFactor, HK_WIDTH),
  897. Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
  898. Force("vectorize.enable", FK_Undefined, HK_FORCE),
  899. TheLoop(L) {
  900. // Populate values with existing loop metadata.
  901. getHintsFromMetadata();
  902. // force-vector-interleave overrides DisableInterleaving.
  903. if (VectorizationInterleave.getNumOccurrences() > 0)
  904. Interleave.Value = VectorizationInterleave;
  905. DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
  906. << "LV: Interleaving disabled by the pass manager\n");
  907. }
  908. /// Mark the loop L as already vectorized by setting the width to 1.
  909. void setAlreadyVectorized() {
  910. Width.Value = Interleave.Value = 1;
  911. Hint Hints[] = {Width, Interleave};
  912. writeHintsToMetadata(Hints);
  913. }
  914. /// Dumps all the hint information.
  915. std::string emitRemark() const {
  916. Report R;
  917. if (Force.Value == LoopVectorizeHints::FK_Disabled)
  918. R << "vectorization is explicitly disabled";
  919. else {
  920. R << "use -Rpass-analysis=loop-vectorize for more info";
  921. if (Force.Value == LoopVectorizeHints::FK_Enabled) {
  922. R << " (Force=true";
  923. if (Width.Value != 0)
  924. R << ", Vector Width=" << Width.Value;
  925. if (Interleave.Value != 0)
  926. R << ", Interleave Count=" << Interleave.Value;
  927. R << ")";
  928. }
  929. }
  930. return R.str();
  931. }
  932. unsigned getWidth() const { return Width.Value; }
  933. unsigned getInterleave() const { return Interleave.Value; }
  934. enum ForceKind getForce() const { return (ForceKind)Force.Value; }
  935. private:
  936. /// Find hints specified in the loop metadata and update local values.
  937. void getHintsFromMetadata() {
  938. MDNode *LoopID = TheLoop->getLoopID();
  939. if (!LoopID)
  940. return;
  941. // First operand should refer to the loop id itself.
  942. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  943. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  944. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  945. const MDString *S = nullptr;
  946. SmallVector<Metadata *, 4> Args;
  947. // The expected hint is either a MDString or a MDNode with the first
  948. // operand a MDString.
  949. if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
  950. if (!MD || MD->getNumOperands() == 0)
  951. continue;
  952. S = dyn_cast<MDString>(MD->getOperand(0));
  953. for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
  954. Args.push_back(MD->getOperand(i));
  955. } else {
  956. S = dyn_cast<MDString>(LoopID->getOperand(i));
  957. assert(Args.size() == 0 && "too many arguments for MDString");
  958. }
  959. if (!S)
  960. continue;
  961. // Check if the hint starts with the loop metadata prefix.
  962. StringRef Name = S->getString();
  963. if (Args.size() == 1)
  964. setHint(Name, Args[0]);
  965. }
  966. }
  967. /// Checks string hint with one operand and set value if valid.
  968. void setHint(StringRef Name, Metadata *Arg) {
  969. if (!Name.startswith(Prefix()))
  970. return;
  971. Name = Name.substr(Prefix().size(), StringRef::npos);
  972. const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
  973. if (!C) return;
  974. unsigned Val = C->getZExtValue();
  975. Hint *Hints[] = {&Width, &Interleave, &Force};
  976. for (auto H : Hints) {
  977. if (Name == H->Name) {
  978. if (H->validate(Val))
  979. H->Value = Val;
  980. else
  981. DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
  982. break;
  983. }
  984. }
  985. }
  986. /// Create a new hint from name / value pair.
  987. MDNode *createHintMetadata(StringRef Name, unsigned V) const {
  988. LLVMContext &Context = TheLoop->getHeader()->getContext();
  989. Metadata *MDs[] = {MDString::get(Context, Name),
  990. ConstantAsMetadata::get(
  991. ConstantInt::get(Type::getInt32Ty(Context), V))};
  992. return MDNode::get(Context, MDs);
  993. }
  994. /// Matches metadata with hint name.
  995. bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
  996. MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
  997. if (!Name)
  998. return false;
  999. for (auto H : HintTypes)
  1000. if (Name->getString().endswith(H.Name))
  1001. return true;
  1002. return false;
  1003. }
  1004. /// Sets current hints into loop metadata, keeping other values intact.
  1005. void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
  1006. if (HintTypes.size() == 0)
  1007. return;
  1008. // Reserve the first element to LoopID (see below).
  1009. SmallVector<Metadata *, 4> MDs(1);
  1010. // If the loop already has metadata, then ignore the existing operands.
  1011. MDNode *LoopID = TheLoop->getLoopID();
  1012. if (LoopID) {
  1013. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  1014. MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
  1015. // If node in update list, ignore old value.
  1016. if (!matchesHintMetadataName(Node, HintTypes))
  1017. MDs.push_back(Node);
  1018. }
  1019. }
  1020. // Now, add the missing hints.
  1021. for (auto H : HintTypes)
  1022. MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
  1023. // Replace current metadata node with new one.
  1024. LLVMContext &Context = TheLoop->getHeader()->getContext();
  1025. MDNode *NewLoopID = MDNode::get(Context, MDs);
  1026. // Set operand 0 to refer to the loop id itself.
  1027. NewLoopID->replaceOperandWith(0, NewLoopID);
  1028. TheLoop->setLoopID(NewLoopID);
  1029. LoopID = NewLoopID;
  1030. }
  1031. /// The loop these hints belong to.
  1032. const Loop *TheLoop;
  1033. };
  1034. static void emitMissedWarning(Function *F, Loop *L,
  1035. const LoopVectorizeHints &LH) {
  1036. emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
  1037. L->getStartLoc(), LH.emitRemark());
  1038. if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
  1039. if (LH.getWidth() != 1)
  1040. emitLoopVectorizeWarning(
  1041. F->getContext(), *F, L->getStartLoc(),
  1042. "failed explicitly specified loop vectorization");
  1043. else if (LH.getInterleave() != 1)
  1044. emitLoopInterleaveWarning(
  1045. F->getContext(), *F, L->getStartLoc(),
  1046. "failed explicitly specified loop interleaving");
  1047. }
  1048. }
  1049. static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
  1050. if (L.empty())
  1051. return V.push_back(&L);
  1052. for (Loop *InnerL : L)
  1053. addInnerLoop(*InnerL, V);
  1054. }
  1055. /// The LoopVectorize Pass.
  1056. struct LoopVectorize : public FunctionPass {
  1057. /// Pass identification, replacement for typeid
  1058. static char ID;
  1059. explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
  1060. : FunctionPass(ID),
  1061. DisableUnrolling(NoUnrolling),
  1062. AlwaysVectorize(AlwaysVectorize) {
  1063. initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
  1064. }
  1065. ScalarEvolution *SE;
  1066. const DataLayout *DL;
  1067. LoopInfo *LI;
  1068. TargetTransformInfo *TTI;
  1069. DominatorTree *DT;
  1070. BlockFrequencyInfo *BFI;
  1071. TargetLibraryInfo *TLI;
  1072. AliasAnalysis *AA;
  1073. AssumptionTracker *AT;
  1074. bool DisableUnrolling;
  1075. bool AlwaysVectorize;
  1076. BlockFrequency ColdEntryFreq;
  1077. bool runOnFunction(Function &F) override {
  1078. SE = &getAnalysis<ScalarEvolution>();
  1079. DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
  1080. DL = DLP ? &DLP->getDataLayout() : nullptr;
  1081. LI = &getAnalysis<LoopInfo>();
  1082. TTI = &getAnalysis<TargetTransformInfo>();
  1083. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1084. BFI = &getAnalysis<BlockFrequencyInfo>();
  1085. TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
  1086. AA = &getAnalysis<AliasAnalysis>();
  1087. AT = &getAnalysis<AssumptionTracker>();
  1088. // Compute some weights outside of the loop over the loops. Compute this
  1089. // using a BranchProbability to re-use its scaling math.
  1090. const BranchProbability ColdProb(1, 5); // 20%
  1091. ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
  1092. // If the target claims to have no vector registers don't attempt
  1093. // vectorization.
  1094. if (!TTI->getNumberOfRegisters(true))
  1095. return false;
  1096. if (!DL) {
  1097. DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
  1098. << ": Missing data layout\n");
  1099. return false;
  1100. }
  1101. // Build up a worklist of inner-loops to vectorize. This is necessary as
  1102. // the act of vectorizing or partially unrolling a loop creates new loops
  1103. // and can invalidate iterators across the loops.
  1104. SmallVector<Loop *, 8> Worklist;
  1105. for (Loop *L : *LI)
  1106. addInnerLoop(*L, Worklist);
  1107. LoopsAnalyzed += Worklist.size();
  1108. // Now walk the identified inner loops.
  1109. bool Changed = false;
  1110. while (!Worklist.empty())
  1111. Changed |= processLoop(Worklist.pop_back_val());
  1112. // Process each loop nest in the function.
  1113. return Changed;
  1114. }
  1115. bool processLoop(Loop *L) {
  1116. assert(L->empty() && "Only process inner loops.");
  1117. #ifndef NDEBUG
  1118. const std::string DebugLocStr = getDebugLocString(L);
  1119. #endif /* NDEBUG */
  1120. DEBUG(dbgs() << "\nLV: Checking a loop in \""
  1121. << L->getHeader()->getParent()->getName() << "\" from "
  1122. << DebugLocStr << "\n");
  1123. LoopVectorizeHints Hints(L, DisableUnrolling);
  1124. DEBUG(dbgs() << "LV: Loop hints:"
  1125. << " force="
  1126. << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
  1127. ? "disabled"
  1128. : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
  1129. ? "enabled"
  1130. : "?")) << " width=" << Hints.getWidth()
  1131. << " unroll=" << Hints.getInterleave() << "\n");
  1132. // Function containing loop
  1133. Function *F = L->getHeader()->getParent();
  1134. // Looking at the diagnostic output is the only way to determine if a loop
  1135. // was vectorized (other than looking at the IR or machine code), so it
  1136. // is important to generate an optimization remark for each loop. Most of
  1137. // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
  1138. // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
  1139. // less verbose reporting vectorized loops and unvectorized loops that may
  1140. // benefit from vectorization, respectively.
  1141. if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
  1142. DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
  1143. emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
  1144. L->getStartLoc(), Hints.emitRemark());
  1145. return false;
  1146. }
  1147. if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
  1148. DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
  1149. emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
  1150. L->getStartLoc(), Hints.emitRemark());
  1151. return false;
  1152. }
  1153. if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
  1154. DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
  1155. emitOptimizationRemarkAnalysis(
  1156. F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
  1157. "loop not vectorized: vector width and interleave count are "
  1158. "explicitly set to 1");
  1159. return false;
  1160. }
  1161. // Check the loop for a trip count threshold:
  1162. // do not vectorize loops with a tiny trip count.
  1163. const unsigned TC = SE->getSmallConstantTripCount(L);
  1164. if (TC > 0u && TC < TinyTripCountVectorThreshold) {
  1165. DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
  1166. << "This loop is not worth vectorizing.");
  1167. if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
  1168. DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
  1169. else {
  1170. DEBUG(dbgs() << "\n");
  1171. emitOptimizationRemarkAnalysis(
  1172. F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
  1173. "vectorization is not beneficial and is not explicitly forced");
  1174. return false;
  1175. }
  1176. }
  1177. // Check if it is legal to vectorize the loop.
  1178. LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F);
  1179. if (!LVL.canVectorize()) {
  1180. DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
  1181. emitMissedWarning(F, L, Hints);
  1182. return false;
  1183. }
  1184. // Use the cost model.
  1185. LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AT, F,
  1186. &Hints);
  1187. // Check the function attributes to find out if this function should be
  1188. // optimized for size.
  1189. bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
  1190. F->hasFnAttribute(Attribute::OptimizeForSize);
  1191. // Compute the weighted frequency of this loop being executed and see if it
  1192. // is less than 20% of the function entry baseline frequency. Note that we
  1193. // always have a canonical loop here because we think we *can* vectoriez.
  1194. // FIXME: This is hidden behind a flag due to pervasive problems with
  1195. // exactly what block frequency models.
  1196. if (LoopVectorizeWithBlockFrequency) {
  1197. BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
  1198. if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
  1199. LoopEntryFreq < ColdEntryFreq)
  1200. OptForSize = true;
  1201. }
  1202. // Check the function attributes to see if implicit floats are allowed.a
  1203. // FIXME: This check doesn't seem possibly correct -- what if the loop is
  1204. // an integer loop and the vector instructions selected are purely integer
  1205. // vector instructions?
  1206. if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
  1207. DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
  1208. "attribute is used.\n");
  1209. emitOptimizationRemarkAnalysis(
  1210. F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
  1211. "loop not vectorized due to NoImplicitFloat attribute");
  1212. emitMissedWarning(F, L, Hints);
  1213. return false;
  1214. }
  1215. // Select the optimal vectorization factor.
  1216. const LoopVectorizationCostModel::VectorizationFactor VF =
  1217. CM.selectVectorizationFactor(OptForSize);
  1218. // Select the unroll factor.
  1219. const unsigned UF =
  1220. CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
  1221. DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
  1222. << DebugLocStr << '\n');
  1223. DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
  1224. if (VF.Width == 1) {
  1225. DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
  1226. if (UF == 1) {
  1227. emitOptimizationRemarkAnalysis(
  1228. F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
  1229. "not beneficial to vectorize and user disabled interleaving");
  1230. return false;
  1231. }
  1232. DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
  1233. // Report the unrolling decision.
  1234. emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
  1235. Twine("unrolled with interleaving factor " +
  1236. Twine(UF) +
  1237. " (vectorization not beneficial)"));
  1238. // We decided not to vectorize, but we may want to unroll.
  1239. InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
  1240. Unroller.vectorize(&LVL);
  1241. } else {
  1242. // If we decided that it is *legal* to vectorize the loop then do it.
  1243. InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
  1244. LB.vectorize(&LVL);
  1245. ++LoopsVectorized;
  1246. // Report the vectorization decision.
  1247. emitOptimizationRemark(
  1248. F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
  1249. Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
  1250. ", unrolling interleave factor: " + Twine(UF) + ")");
  1251. }
  1252. // Mark the loop as already vectorized to avoid vectorizing again.
  1253. Hints.setAlreadyVectorized();
  1254. DEBUG(verifyFunction(*L->getHeader()->getParent()));
  1255. return true;
  1256. }
  1257. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1258. AU.addRequired<AssumptionTracker>();
  1259. AU.addRequiredID(LoopSimplifyID);
  1260. AU.addRequiredID(LCSSAID);
  1261. AU.addRequired<BlockFrequencyInfo>();
  1262. AU.addRequired<DominatorTreeWrapperPass>();
  1263. AU.addRequired<LoopInfo>();
  1264. AU.addRequired<ScalarEvolution>();
  1265. AU.addRequired<TargetTransformInfo>();
  1266. AU.addRequired<AliasAnalysis>();
  1267. AU.addPreserved<LoopInfo>();
  1268. AU.addPreserved<DominatorTreeWrapperPass>();
  1269. AU.addPreserved<AliasAnalysis>();
  1270. }
  1271. };
  1272. } // end anonymous namespace
  1273. //===----------------------------------------------------------------------===//
  1274. // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
  1275. // LoopVectorizationCostModel.
  1276. //===----------------------------------------------------------------------===//
  1277. static Value *stripIntegerCast(Value *V) {
  1278. if (CastInst *CI = dyn_cast<CastInst>(V))
  1279. if (CI->getOperand(0)->getType()->isIntegerTy())
  1280. return CI->getOperand(0);
  1281. return V;
  1282. }
  1283. ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
  1284. ///
  1285. /// If \p OrigPtr is not null, use it to look up the stride value instead of
  1286. /// \p Ptr.
  1287. static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
  1288. ValueToValueMap &PtrToStride,
  1289. Value *Ptr, Value *OrigPtr = nullptr) {
  1290. const SCEV *OrigSCEV = SE->getSCEV(Ptr);
  1291. // If there is an entry in the map return the SCEV of the pointer with the
  1292. // symbolic stride replaced by one.
  1293. ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
  1294. if (SI != PtrToStride.end()) {
  1295. Value *StrideVal = SI->second;
  1296. // Strip casts.
  1297. StrideVal = stripIntegerCast(StrideVal);
  1298. // Replace symbolic stride by one.
  1299. Value *One = ConstantInt::get(StrideVal->getType(), 1);
  1300. ValueToValueMap RewriteMap;
  1301. RewriteMap[StrideVal] = One;
  1302. const SCEV *ByOne =
  1303. SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
  1304. DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
  1305. << "\n");
  1306. return ByOne;
  1307. }
  1308. // Otherwise, just return the SCEV of the original pointer.
  1309. return SE->getSCEV(Ptr);
  1310. }
  1311. void LoopVectorizationLegality::RuntimePointerCheck::insert(
  1312. ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
  1313. unsigned ASId, ValueToValueMap &Strides) {
  1314. // Get the stride replaced scev.
  1315. const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
  1316. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
  1317. assert(AR && "Invalid addrec expression");
  1318. const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
  1319. const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
  1320. Pointers.push_back(Ptr);
  1321. Starts.push_back(AR->getStart());
  1322. Ends.push_back(ScEnd);
  1323. IsWritePtr.push_back(WritePtr);
  1324. DependencySetId.push_back(DepSetId);
  1325. AliasSetId.push_back(ASId);
  1326. }
  1327. Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
  1328. // We need to place the broadcast of invariant variables outside the loop.
  1329. Instruction *Instr = dyn_cast<Instruction>(V);
  1330. bool NewInstr =
  1331. (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
  1332. Instr->getParent()) != LoopVectorBody.end());
  1333. bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
  1334. // Place the code for broadcasting invariant variables in the new preheader.
  1335. IRBuilder<>::InsertPointGuard Guard(Builder);
  1336. if (Invariant)
  1337. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1338. // Broadcast the scalar into all locations in the vector.
  1339. Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
  1340. return Shuf;
  1341. }
  1342. Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
  1343. bool Negate) {
  1344. assert(Val->getType()->isVectorTy() && "Must be a vector");
  1345. assert(Val->getType()->getScalarType()->isIntegerTy() &&
  1346. "Elem must be an integer");
  1347. // Create the types.
  1348. Type *ITy = Val->getType()->getScalarType();
  1349. VectorType *Ty = cast<VectorType>(Val->getType());
  1350. int VLen = Ty->getNumElements();
  1351. SmallVector<Constant*, 8> Indices;
  1352. // Create a vector of consecutive numbers from zero to VF.
  1353. for (int i = 0; i < VLen; ++i) {
  1354. int64_t Idx = Negate ? (-i) : i;
  1355. Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
  1356. }
  1357. // Add the consecutive indices to the vector value.
  1358. Constant *Cv = ConstantVector::get(Indices);
  1359. assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
  1360. return Builder.CreateAdd(Val, Cv, "induction");
  1361. }
  1362. /// \brief Find the operand of the GEP that should be checked for consecutive
  1363. /// stores. This ignores trailing indices that have no effect on the final
  1364. /// pointer.
  1365. static unsigned getGEPInductionOperand(const DataLayout *DL,
  1366. const GetElementPtrInst *Gep) {
  1367. unsigned LastOperand = Gep->getNumOperands() - 1;
  1368. unsigned GEPAllocSize = DL->getTypeAllocSize(
  1369. cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
  1370. // Walk backwards and try to peel off zeros.
  1371. while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
  1372. // Find the type we're currently indexing into.
  1373. gep_type_iterator GEPTI = gep_type_begin(Gep);
  1374. std::advance(GEPTI, LastOperand - 1);
  1375. // If it's a type with the same allocation size as the result of the GEP we
  1376. // can peel off the zero index.
  1377. if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
  1378. break;
  1379. --LastOperand;
  1380. }
  1381. return LastOperand;
  1382. }
  1383. int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
  1384. assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
  1385. // Make sure that the pointer does not point to structs.
  1386. if (Ptr->getType()->getPointerElementType()->isAggregateType())
  1387. return 0;
  1388. // If this value is a pointer induction variable we know it is consecutive.
  1389. PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
  1390. if (Phi && Inductions.count(Phi)) {
  1391. InductionInfo II = Inductions[Phi];
  1392. if (IK_PtrInduction == II.IK)
  1393. return 1;
  1394. else if (IK_ReversePtrInduction == II.IK)
  1395. return -1;
  1396. }
  1397. GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
  1398. if (!Gep)
  1399. return 0;
  1400. unsigned NumOperands = Gep->getNumOperands();
  1401. Value *GpPtr = Gep->getPointerOperand();
  1402. // If this GEP value is a consecutive pointer induction variable and all of
  1403. // the indices are constant then we know it is consecutive. We can
  1404. Phi = dyn_cast<PHINode>(GpPtr);
  1405. if (Phi && Inductions.count(Phi)) {
  1406. // Make sure that the pointer does not point to structs.
  1407. PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
  1408. if (GepPtrType->getElementType()->isAggregateType())
  1409. return 0;
  1410. // Make sure that all of the index operands are loop invariant.
  1411. for (unsigned i = 1; i < NumOperands; ++i)
  1412. if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
  1413. return 0;
  1414. InductionInfo II = Inductions[Phi];
  1415. if (IK_PtrInduction == II.IK)
  1416. return 1;
  1417. else if (IK_ReversePtrInduction == II.IK)
  1418. return -1;
  1419. }
  1420. unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
  1421. // Check that all of the gep indices are uniform except for our induction
  1422. // operand.
  1423. for (unsigned i = 0; i != NumOperands; ++i)
  1424. if (i != InductionOperand &&
  1425. !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
  1426. return 0;
  1427. // We can emit wide load/stores only if the last non-zero index is the
  1428. // induction variable.
  1429. const SCEV *Last = nullptr;
  1430. if (!Strides.count(Gep))
  1431. Last = SE->getSCEV(Gep->getOperand(InductionOperand));
  1432. else {
  1433. // Because of the multiplication by a stride we can have a s/zext cast.
  1434. // We are going to replace this stride by 1 so the cast is safe to ignore.
  1435. //
  1436. // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
  1437. // %0 = trunc i64 %indvars.iv to i32
  1438. // %mul = mul i32 %0, %Stride1
  1439. // %idxprom = zext i32 %mul to i64 << Safe cast.
  1440. // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
  1441. //
  1442. Last = replaceSymbolicStrideSCEV(SE, Strides,
  1443. Gep->getOperand(InductionOperand), Gep);
  1444. if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
  1445. Last =
  1446. (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
  1447. ? C->getOperand()
  1448. : Last;
  1449. }
  1450. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
  1451. const SCEV *Step = AR->getStepRecurrence(*SE);
  1452. // The memory is consecutive because the last index is consecutive
  1453. // and all other indices are loop invariant.
  1454. if (Step->isOne())
  1455. return 1;
  1456. if (Step->isAllOnesValue())
  1457. return -1;
  1458. }
  1459. return 0;
  1460. }
  1461. bool LoopVectorizationLegality::isUniform(Value *V) {
  1462. return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
  1463. }
  1464. InnerLoopVectorizer::VectorParts&
  1465. InnerLoopVectorizer::getVectorValue(Value *V) {
  1466. assert(V != Induction && "The new induction variable should not be used.");
  1467. assert(!V->getType()->isVectorTy() && "Can't widen a vector");
  1468. // If we have a stride that is replaced by one, do it here.
  1469. if (Legal->hasStride(V))
  1470. V = ConstantInt::get(V->getType(), 1);
  1471. // If we have this scalar in the map, return it.
  1472. if (WidenMap.has(V))
  1473. return WidenMap.get(V);
  1474. // If this scalar is unknown, assume that it is a constant or that it is
  1475. // loop invariant. Broadcast V and save the value for future uses.
  1476. Value *B = getBroadcastInstrs(V);
  1477. return WidenMap.splat(V, B);
  1478. }
  1479. Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
  1480. assert(Vec->getType()->isVectorTy() && "Invalid type");
  1481. SmallVector<Constant*, 8> ShuffleMask;
  1482. for (unsigned i = 0; i < VF; ++i)
  1483. ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
  1484. return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
  1485. ConstantVector::get(ShuffleMask),
  1486. "reverse");
  1487. }
  1488. void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
  1489. // Attempt to issue a wide load.
  1490. LoadInst *LI = dyn_cast<LoadInst>(Instr);
  1491. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  1492. assert((LI || SI) && "Invalid Load/Store instruction");
  1493. Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
  1494. Type *DataTy = VectorType::get(ScalarDataTy, VF);
  1495. Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
  1496. unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
  1497. // An alignment of 0 means target abi alignment. We need to use the scalar's
  1498. // target abi alignment in such a case.
  1499. if (!Alignment)
  1500. Alignment = DL->getABITypeAlignment(ScalarDataTy);
  1501. unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
  1502. unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
  1503. unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
  1504. if (SI && Legal->blockNeedsPredication(SI->getParent()))
  1505. return scalarizeInstruction(Instr, true);
  1506. if (ScalarAllocatedSize != VectorElementSize)
  1507. return scalarizeInstruction(Instr);
  1508. // If the pointer is loop invariant or if it is non-consecutive,
  1509. // scalarize the load.
  1510. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  1511. bool Reverse = ConsecutiveStride < 0;
  1512. bool UniformLoad = LI && Legal->isUniform(Ptr);
  1513. if (!ConsecutiveStride || UniformLoad)
  1514. return scalarizeInstruction(Instr);
  1515. Constant *Zero = Builder.getInt32(0);
  1516. VectorParts &Entry = WidenMap.get(Instr);
  1517. // Handle consecutive loads/stores.
  1518. GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  1519. if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
  1520. setDebugLocFromInst(Builder, Gep);
  1521. Value *PtrOperand = Gep->getPointerOperand();
  1522. Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
  1523. FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
  1524. // Create the new GEP with the new induction variable.
  1525. GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
  1526. Gep2->setOperand(0, FirstBasePtr);
  1527. Gep2->setName("gep.indvar.base");
  1528. Ptr = Builder.Insert(Gep2);
  1529. } else if (Gep) {
  1530. setDebugLocFromInst(Builder, Gep);
  1531. assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
  1532. OrigLoop) && "Base ptr must be invariant");
  1533. // The last index does not have to be the induction. It can be
  1534. // consecutive and be a function of the index. For example A[I+1];
  1535. unsigned NumOperands = Gep->getNumOperands();
  1536. unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
  1537. // Create the new GEP with the new induction variable.
  1538. GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
  1539. for (unsigned i = 0; i < NumOperands; ++i) {
  1540. Value *GepOperand = Gep->getOperand(i);
  1541. Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
  1542. // Update last index or loop invariant instruction anchored in loop.
  1543. if (i == InductionOperand ||
  1544. (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
  1545. assert((i == InductionOperand ||
  1546. SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
  1547. "Must be last index or loop invariant");
  1548. VectorParts &GEPParts = getVectorValue(GepOperand);
  1549. Value *Index = GEPParts[0];
  1550. Index = Builder.CreateExtractElement(Index, Zero);
  1551. Gep2->setOperand(i, Index);
  1552. Gep2->setName("gep.indvar.idx");
  1553. }
  1554. }
  1555. Ptr = Builder.Insert(Gep2);
  1556. } else {
  1557. // Use the induction element ptr.
  1558. assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
  1559. setDebugLocFromInst(Builder, Ptr);
  1560. VectorParts &PtrVal = getVectorValue(Ptr);
  1561. Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
  1562. }
  1563. // Handle Stores:
  1564. if (SI) {
  1565. assert(!Legal->isUniform(SI->getPointerOperand()) &&
  1566. "We do not allow storing to uniform addresses");
  1567. setDebugLocFromInst(Builder, SI);
  1568. // We don't want to update the value in the map as it might be used in
  1569. // another expression. So don't use a reference type for "StoredVal".
  1570. VectorParts StoredVal = getVectorValue(SI->getValueOperand());
  1571. for (unsigned Part = 0; Part < UF; ++Part) {
  1572. // Calculate the pointer for the specific unroll-part.
  1573. Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
  1574. if (Reverse) {
  1575. // If we store to reverse consecutive memory locations then we need
  1576. // to reverse the order of elements in the stored value.
  1577. StoredVal[Part] = reverseVector(StoredVal[Part]);
  1578. // If the address is consecutive but reversed, then the
  1579. // wide store needs to start at the last vector element.
  1580. PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
  1581. PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
  1582. }
  1583. Value *VecPtr = Builder.CreateBitCast(PartPtr,
  1584. DataTy->getPointerTo(AddressSpace));
  1585. StoreInst *NewSI =
  1586. Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
  1587. propagateMetadata(NewSI, SI);
  1588. }
  1589. return;
  1590. }
  1591. // Handle loads.
  1592. assert(LI && "Must have a load instruction");
  1593. setDebugLocFromInst(Builder, LI);
  1594. for (unsigned Part = 0; Part < UF; ++Part) {
  1595. // Calculate the pointer for the specific unroll-part.
  1596. Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
  1597. if (Reverse) {
  1598. // If the address is consecutive but reversed, then the
  1599. // wide store needs to start at the last vector element.
  1600. PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
  1601. PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
  1602. }
  1603. Value *VecPtr = Builder.CreateBitCast(PartPtr,
  1604. DataTy->getPointerTo(AddressSpace));
  1605. LoadInst *NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
  1606. propagateMetadata(NewLI, LI);
  1607. Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
  1608. }
  1609. }
  1610. void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
  1611. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  1612. // Holds vector parameters or scalars, in case of uniform vals.
  1613. SmallVector<VectorParts, 4> Params;
  1614. setDebugLocFromInst(Builder, Instr);
  1615. // Find all of the vectorized parameters.
  1616. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  1617. Value *SrcOp = Instr->getOperand(op);
  1618. // If we are accessing the old induction variable, use the new one.
  1619. if (SrcOp == OldInduction) {
  1620. Params.push_back(getVectorValue(SrcOp));
  1621. continue;
  1622. }
  1623. // Try using previously calculated values.
  1624. Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
  1625. // If the src is an instruction that appeared earlier in the basic block
  1626. // then it should already be vectorized.
  1627. if (SrcInst && OrigLoop->contains(SrcInst)) {
  1628. assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
  1629. // The parameter is a vector value from earlier.
  1630. Params.push_back(WidenMap.get(SrcInst));
  1631. } else {
  1632. // The parameter is a scalar from outside the loop. Maybe even a constant.
  1633. VectorParts Scalars;
  1634. Scalars.append(UF, SrcOp);
  1635. Params.push_back(Scalars);
  1636. }
  1637. }
  1638. assert(Params.size() == Instr->getNumOperands() &&
  1639. "Invalid number of operands");
  1640. // Does this instruction return a value ?
  1641. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  1642. Value *UndefVec = IsVoidRetTy ? nullptr :
  1643. UndefValue::get(VectorType::get(Instr->getType(), VF));
  1644. // Create a new entry in the WidenMap and initialize it to Undef or Null.
  1645. VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
  1646. Instruction *InsertPt = Builder.GetInsertPoint();
  1647. BasicBlock *IfBlock = Builder.GetInsertBlock();
  1648. BasicBlock *CondBlock = nullptr;
  1649. VectorParts Cond;
  1650. Loop *VectorLp = nullptr;
  1651. if (IfPredicateStore) {
  1652. assert(Instr->getParent()->getSinglePredecessor() &&
  1653. "Only support single predecessor blocks");
  1654. Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
  1655. Instr->getParent());
  1656. VectorLp = LI->getLoopFor(IfBlock);
  1657. assert(VectorLp && "Must have a loop for this block");
  1658. }
  1659. // For each vector unroll 'part':
  1660. for (unsigned Part = 0; Part < UF; ++Part) {
  1661. // For each scalar that we create:
  1662. for (unsigned Width = 0; Width < VF; ++Width) {
  1663. // Start if-block.
  1664. Value *Cmp = nullptr;
  1665. if (IfPredicateStore) {
  1666. Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
  1667. Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
  1668. CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
  1669. LoopVectorBody.push_back(CondBlock);
  1670. VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
  1671. // Update Builder with newly created basic block.
  1672. Builder.SetInsertPoint(InsertPt);
  1673. }
  1674. Instruction *Cloned = Instr->clone();
  1675. if (!IsVoidRetTy)
  1676. Cloned->setName(Instr->getName() + ".cloned");
  1677. // Replace the operands of the cloned instructions with extracted scalars.
  1678. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  1679. Value *Op = Params[op][Part];
  1680. // Param is a vector. Need to extract the right lane.
  1681. if (Op->getType()->isVectorTy())
  1682. Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
  1683. Cloned->setOperand(op, Op);
  1684. }
  1685. // Place the cloned scalar in the new loop.
  1686. Builder.Insert(Cloned);
  1687. // If the original scalar returns a value we need to place it in a vector
  1688. // so that future users will be able to use it.
  1689. if (!IsVoidRetTy)
  1690. VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
  1691. Builder.getInt32(Width));
  1692. // End if-block.
  1693. if (IfPredicateStore) {
  1694. BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
  1695. LoopVectorBody.push_back(NewIfBlock);
  1696. VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
  1697. Builder.SetInsertPoint(InsertPt);
  1698. Instruction *OldBr = IfBlock->getTerminator();
  1699. BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
  1700. OldBr->eraseFromParent();
  1701. IfBlock = NewIfBlock;
  1702. }
  1703. }
  1704. }
  1705. }
  1706. static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
  1707. Instruction *Loc) {
  1708. if (FirstInst)
  1709. return FirstInst;
  1710. if (Instruction *I = dyn_cast<Instruction>(V))
  1711. return I->getParent() == Loc->getParent() ? I : nullptr;
  1712. return nullptr;
  1713. }
  1714. std::pair<Instruction *, Instruction *>
  1715. InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
  1716. Instruction *tnullptr = nullptr;
  1717. if (!Legal->mustCheckStrides())
  1718. return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
  1719. IRBuilder<> ChkBuilder(Loc);
  1720. // Emit checks.
  1721. Value *Check = nullptr;
  1722. Instruction *FirstInst = nullptr;
  1723. for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
  1724. SE = Legal->strides_end();
  1725. SI != SE; ++SI) {
  1726. Value *Ptr = stripIntegerCast(*SI);
  1727. Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
  1728. "stride.chk");
  1729. // Store the first instruction we create.
  1730. FirstInst = getFirstInst(FirstInst, C, Loc);
  1731. if (Check)
  1732. Check = ChkBuilder.CreateOr(Check, C);
  1733. else
  1734. Check = C;
  1735. }
  1736. // We have to do this trickery because the IRBuilder might fold the check to a
  1737. // constant expression in which case there is no Instruction anchored in a
  1738. // the block.
  1739. LLVMContext &Ctx = Loc->getContext();
  1740. Instruction *TheCheck =
  1741. BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
  1742. ChkBuilder.Insert(TheCheck, "stride.not.one");
  1743. FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
  1744. return std::make_pair(FirstInst, TheCheck);
  1745. }
  1746. std::pair<Instruction *, Instruction *>
  1747. InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
  1748. LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
  1749. Legal->getRuntimePointerCheck();
  1750. Instruction *tnullptr = nullptr;
  1751. if (!PtrRtCheck->Need)
  1752. return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
  1753. unsigned NumPointers = PtrRtCheck->Pointers.size();
  1754. SmallVector<TrackingVH<Value> , 2> Starts;
  1755. SmallVector<TrackingVH<Value> , 2> Ends;
  1756. LLVMContext &Ctx = Loc->getContext();
  1757. SCEVExpander Exp(*SE, "induction");
  1758. Instruction *FirstInst = nullptr;
  1759. for (unsigned i = 0; i < NumPointers; ++i) {
  1760. Value *Ptr = PtrRtCheck->Pointers[i];
  1761. const SCEV *Sc = SE->getSCEV(Ptr);
  1762. if (SE->isLoopInvariant(Sc, OrigLoop)) {
  1763. DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
  1764. *Ptr <<"\n");
  1765. Starts.push_back(Ptr);
  1766. Ends.push_back(Ptr);
  1767. } else {
  1768. DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
  1769. unsigned AS = Ptr->getType()->getPointerAddressSpace();
  1770. // Use this type for pointer arithmetic.
  1771. Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
  1772. Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
  1773. Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
  1774. Starts.push_back(Start);
  1775. Ends.push_back(End);
  1776. }
  1777. }
  1778. IRBuilder<> ChkBuilder(Loc);
  1779. // Our instructions might fold to a constant.
  1780. Value *MemoryRuntimeCheck = nullptr;
  1781. for (unsigned i = 0; i < NumPointers; ++i) {
  1782. for (unsigned j = i+1; j < NumPointers; ++j) {
  1783. // No need to check if two readonly pointers intersect.
  1784. if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
  1785. continue;
  1786. // Only need to check pointers between two different dependency sets.
  1787. if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
  1788. continue;
  1789. // Only need to check pointers in the same alias set.
  1790. if (PtrRtCheck->AliasSetId[i] != PtrRtCheck->AliasSetId[j])
  1791. continue;
  1792. unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
  1793. unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
  1794. assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
  1795. (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
  1796. "Trying to bounds check pointers with different address spaces");
  1797. Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
  1798. Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
  1799. Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
  1800. Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
  1801. Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
  1802. Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
  1803. Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
  1804. FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
  1805. Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
  1806. FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
  1807. Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
  1808. FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
  1809. if (MemoryRuntimeCheck) {
  1810. IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
  1811. "conflict.rdx");
  1812. FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
  1813. }
  1814. MemoryRuntimeCheck = IsConflict;
  1815. }
  1816. }
  1817. // We have to do this trickery because the IRBuilder might fold the check to a
  1818. // constant expression in which case there is no Instruction anchored in a
  1819. // the block.
  1820. Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
  1821. ConstantInt::getTrue(Ctx));
  1822. ChkBuilder.Insert(Check, "memcheck.conflict");
  1823. FirstInst = getFirstInst(FirstInst, Check, Loc);
  1824. return std::make_pair(FirstInst, Check);
  1825. }
  1826. void InnerLoopVectorizer::createEmptyLoop() {
  1827. /*
  1828. In this function we generate a new loop. The new loop will contain
  1829. the vectorized instructions while the old loop will continue to run the
  1830. scalar remainder.
  1831. [ ] <-- Back-edge taken count overflow check.
  1832. / |
  1833. / v
  1834. | [ ] <-- vector loop bypass (may consist of multiple blocks).
  1835. | / |
  1836. | / v
  1837. || [ ] <-- vector pre header.
  1838. || |
  1839. || v
  1840. || [ ] \
  1841. || [ ]_| <-- vector loop.
  1842. || |
  1843. | \ v
  1844. | >[ ] <--- middle-block.
  1845. | / |
  1846. | / v
  1847. -|- >[ ] <--- new preheader.
  1848. | |
  1849. | v
  1850. | [ ] \
  1851. | [ ]_| <-- old scalar loop to handle remainder.
  1852. \ |
  1853. \ v
  1854. >[ ] <-- exit block.
  1855. ...
  1856. */
  1857. BasicBlock *OldBasicBlock = OrigLoop->getHeader();
  1858. BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
  1859. BasicBlock *ExitBlock = OrigLoop->getExitBlock();
  1860. assert(BypassBlock && "Invalid loop structure");
  1861. assert(ExitBlock && "Must have an exit block");
  1862. // Some loops have a single integer induction variable, while other loops
  1863. // don't. One example is c++ iterators that often have multiple pointer
  1864. // induction variables. In the code below we also support a case where we
  1865. // don't have a single induction variable.
  1866. OldInduction = Legal->getInduction();
  1867. Type *IdxTy = Legal->getWidestInductionType();
  1868. // Find the loop boundaries.
  1869. const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
  1870. assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
  1871. // The exit count might have the type of i64 while the phi is i32. This can
  1872. // happen if we have an induction variable that is sign extended before the
  1873. // compare. The only way that we get a backedge taken count is that the
  1874. // induction variable was signed and as such will not overflow. In such a case
  1875. // truncation is legal.
  1876. if (ExitCount->getType()->getPrimitiveSizeInBits() >
  1877. IdxTy->getPrimitiveSizeInBits())
  1878. ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
  1879. const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
  1880. // Get the total trip count from the count by adding 1.
  1881. ExitCount = SE->getAddExpr(BackedgeTakeCount,
  1882. SE->getConstant(BackedgeTakeCount->getType(), 1));
  1883. // Expand the trip count and place the new instructions in the preheader.
  1884. // Notice that the pre-header does not change, only the loop body.
  1885. SCEVExpander Exp(*SE, "induction");
  1886. // We need to test whether the backedge-taken count is uint##_max. Adding one
  1887. // to it will cause overflow and an incorrect loop trip count in the vector
  1888. // body. In case of overflow we want to directly jump to the scalar remainder
  1889. // loop.
  1890. Value *BackedgeCount =
  1891. Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
  1892. BypassBlock->getTerminator());
  1893. if (BackedgeCount->getType()->isPointerTy())
  1894. BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
  1895. "backedge.ptrcnt.to.int",
  1896. BypassBlock->getTerminator());
  1897. Instruction *CheckBCOverflow =
  1898. CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
  1899. Constant::getAllOnesValue(BackedgeCount->getType()),
  1900. "backedge.overflow", BypassBlock->getTerminator());
  1901. // The loop index does not have to start at Zero. Find the original start
  1902. // value from the induction PHI node. If we don't have an induction variable
  1903. // then we know that it starts at zero.
  1904. Builder.SetInsertPoint(BypassBlock->getTerminator());
  1905. Value *StartIdx = ExtendedIdx = OldInduction ?
  1906. Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
  1907. IdxTy):
  1908. ConstantInt::get(IdxTy, 0);
  1909. // We need an instruction to anchor the overflow check on. StartIdx needs to
  1910. // be defined before the overflow check branch. Because the scalar preheader
  1911. // is going to merge the start index and so the overflow branch block needs to
  1912. // contain a definition of the start index.
  1913. Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
  1914. StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
  1915. BypassBlock->getTerminator());
  1916. // Count holds the overall loop count (N).
  1917. Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
  1918. BypassBlock->getTerminator());
  1919. LoopBypassBlocks.push_back(BypassBlock);
  1920. // Split the single block loop into the two loop structure described above.
  1921. BasicBlock *VectorPH =
  1922. BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
  1923. BasicBlock *VecBody =
  1924. VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
  1925. BasicBlock *MiddleBlock =
  1926. VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
  1927. BasicBlock *ScalarPH =
  1928. MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
  1929. // Create and register the new vector loop.
  1930. Loop* Lp = new Loop();
  1931. Loop *ParentLoop = OrigLoop->getParentLoop();
  1932. // Insert the new loop into the loop nest and register the new basic blocks
  1933. // before calling any utilities such as SCEV that require valid LoopInfo.
  1934. if (ParentLoop) {
  1935. ParentLoop->addChildLoop(Lp);
  1936. ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
  1937. ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
  1938. ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
  1939. } else {
  1940. LI->addTopLevelLoop(Lp);
  1941. }
  1942. Lp->addBasicBlockToLoop(VecBody, LI->getBase());
  1943. // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
  1944. // inside the loop.
  1945. Builder.SetInsertPoint(VecBody->getFirstNonPHI());
  1946. // Generate the induction variable.
  1947. setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
  1948. Induction = Builder.CreatePHI(IdxTy, 2, "index");
  1949. // The loop step is equal to the vectorization factor (num of SIMD elements)
  1950. // times the unroll factor (num of SIMD instructions).
  1951. Constant *Step = ConstantInt::get(IdxTy, VF * UF);
  1952. // This is the IR builder that we use to add all of the logic for bypassing
  1953. // the new vector loop.
  1954. IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
  1955. setDebugLocFromInst(BypassBuilder,
  1956. getDebugLocFromInstOrOperands(OldInduction));
  1957. // We may need to extend the index in case there is a type mismatch.
  1958. // We know that the count starts at zero and does not overflow.
  1959. if (Count->getType() != IdxTy) {
  1960. // The exit count can be of pointer type. Convert it to the correct
  1961. // integer type.
  1962. if (ExitCount->getType()->isPointerTy())
  1963. Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
  1964. else
  1965. Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
  1966. }
  1967. // Add the start index to the loop count to get the new end index.
  1968. Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
  1969. // Now we need to generate the expression for N - (N % VF), which is
  1970. // the part that the vectorized body will execute.
  1971. Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
  1972. Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
  1973. Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
  1974. "end.idx.rnd.down");
  1975. // Now, compare the new count to zero. If it is zero skip the vector loop and
  1976. // jump to the scalar loop.
  1977. Value *Cmp =
  1978. BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
  1979. BasicBlock *LastBypassBlock = BypassBlock;
  1980. // Generate code to check that the loops trip count that we computed by adding
  1981. // one to the backedge-taken count will not overflow.
  1982. {
  1983. auto PastOverflowCheck =
  1984. std::next(BasicBlock::iterator(OverflowCheckAnchor));
  1985. BasicBlock *CheckBlock =
  1986. LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
  1987. if (ParentLoop)
  1988. ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
  1989. LoopBypassBlocks.push_back(CheckBlock);
  1990. Instruction *OldTerm = LastBypassBlock->getTerminator();
  1991. BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
  1992. OldTerm->eraseFromParent();
  1993. LastBypassBlock = CheckBlock;
  1994. }
  1995. // Generate the code to check that the strides we assumed to be one are really
  1996. // one. We want the new basic block to start at the first instruction in a
  1997. // sequence of instructions that form a check.
  1998. Instruction *StrideCheck;
  1999. Instruction *FirstCheckInst;
  2000. std::tie(FirstCheckInst, StrideCheck) =
  2001. addStrideCheck(LastBypassBlock->getTerminator());
  2002. if (StrideCheck) {
  2003. // Create a new block containing the stride check.
  2004. BasicBlock *CheckBlock =
  2005. LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
  2006. if (ParentLoop)
  2007. ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
  2008. LoopBypassBlocks.push_back(CheckBlock);
  2009. // Replace the branch into the memory check block with a conditional branch
  2010. // for the "few elements case".
  2011. Instruction *OldTerm = LastBypassBlock->getTerminator();
  2012. BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
  2013. OldTerm->eraseFromParent();
  2014. Cmp = StrideCheck;
  2015. LastBypassBlock = CheckBlock;
  2016. }
  2017. // Generate the code that checks in runtime if arrays overlap. We put the
  2018. // checks into a separate block to make the more common case of few elements
  2019. // faster.
  2020. Instruction *MemRuntimeCheck;
  2021. std::tie(FirstCheckInst, MemRuntimeCheck) =
  2022. addRuntimeCheck(LastBypassBlock->getTerminator());
  2023. if (MemRuntimeCheck) {
  2024. // Create a new block containing the memory check.
  2025. BasicBlock *CheckBlock =
  2026. LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
  2027. if (ParentLoop)
  2028. ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
  2029. LoopBypassBlocks.push_back(CheckBlock);
  2030. // Replace the branch into the memory check block with a conditional branch
  2031. // for the "few elements case".
  2032. Instruction *OldTerm = LastBypassBlock->getTerminator();
  2033. BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
  2034. OldTerm->eraseFromParent();
  2035. Cmp = MemRuntimeCheck;
  2036. LastBypassBlock = CheckBlock;
  2037. }
  2038. LastBypassBlock->getTerminator()->eraseFromParent();
  2039. BranchInst::Create(MiddleBlock, VectorPH, Cmp,
  2040. LastBypassBlock);
  2041. // We are going to resume the execution of the scalar loop.
  2042. // Go over all of the induction variables that we found and fix the
  2043. // PHIs that are left in the scalar version of the loop.
  2044. // The starting values of PHI nodes depend on the counter of the last
  2045. // iteration in the vectorized loop.
  2046. // If we come from a bypass edge then we need to start from the original
  2047. // start value.
  2048. // This variable saves the new starting index for the scalar loop.
  2049. PHINode *ResumeIndex = nullptr;
  2050. LoopVectorizationLegality::InductionList::iterator I, E;
  2051. LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
  2052. // Set builder to point to last bypass block.
  2053. BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
  2054. for (I = List->begin(), E = List->end(); I != E; ++I) {
  2055. PHINode *OrigPhi = I->first;
  2056. LoopVectorizationLegality::InductionInfo II = I->second;
  2057. Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
  2058. PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
  2059. MiddleBlock->getTerminator());
  2060. // We might have extended the type of the induction variable but we need a
  2061. // truncated version for the scalar loop.
  2062. PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
  2063. PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
  2064. MiddleBlock->getTerminator()) : nullptr;
  2065. // Create phi nodes to merge from the backedge-taken check block.
  2066. PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
  2067. ScalarPH->getTerminator());
  2068. BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
  2069. PHINode *BCTruncResumeVal = nullptr;
  2070. if (OrigPhi == OldInduction) {
  2071. BCTruncResumeVal =
  2072. PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
  2073. ScalarPH->getTerminator());
  2074. BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
  2075. }
  2076. Value *EndValue = nullptr;
  2077. switch (II.IK) {
  2078. case LoopVectorizationLegality::IK_NoInduction:
  2079. llvm_unreachable("Unknown induction");
  2080. case LoopVectorizationLegality::IK_IntInduction: {
  2081. // Handle the integer induction counter.
  2082. assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
  2083. // We have the canonical induction variable.
  2084. if (OrigPhi == OldInduction) {
  2085. // Create a truncated version of the resume value for the scalar loop,
  2086. // we might have promoted the type to a larger width.
  2087. EndValue =
  2088. BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
  2089. // The new PHI merges the original incoming value, in case of a bypass,
  2090. // or the value at the end of the vectorized loop.
  2091. for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
  2092. TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
  2093. TruncResumeVal->addIncoming(EndValue, VecBody);
  2094. BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
  2095. // We know what the end value is.
  2096. EndValue = IdxEndRoundDown;
  2097. // We also know which PHI node holds it.
  2098. ResumeIndex = ResumeVal;
  2099. break;
  2100. }
  2101. // Not the canonical induction variable - add the vector loop count to the
  2102. // start value.
  2103. Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
  2104. II.StartValue->getType(),
  2105. "cast.crd");
  2106. EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
  2107. break;
  2108. }
  2109. case LoopVectorizationLegality::IK_ReverseIntInduction: {
  2110. // Convert the CountRoundDown variable to the PHI size.
  2111. Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
  2112. II.StartValue->getType(),
  2113. "cast.crd");
  2114. // Handle reverse integer induction counter.
  2115. EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
  2116. break;
  2117. }
  2118. case LoopVectorizationLegality::IK_PtrInduction: {
  2119. // For pointer induction variables, calculate the offset using
  2120. // the end index.
  2121. EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
  2122. "ptr.ind.end");
  2123. break;
  2124. }
  2125. case LoopVectorizationLegality::IK_ReversePtrInduction: {
  2126. // The value at the end of the loop for the reverse pointer is calculated
  2127. // by creating a GEP with a negative index starting from the start value.
  2128. Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
  2129. Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
  2130. "rev.ind.end");
  2131. EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
  2132. "rev.ptr.ind.end");
  2133. break;
  2134. }
  2135. }// end of case
  2136. // The new PHI merges the original incoming value, in case of a bypass,
  2137. // or the value at the end of the vectorized loop.
  2138. for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
  2139. if (OrigPhi == OldInduction)
  2140. ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
  2141. else
  2142. ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
  2143. }
  2144. ResumeVal->addIncoming(EndValue, VecBody);
  2145. // Fix the scalar body counter (PHI node).
  2146. unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
  2147. // The old induction's phi node in the scalar body needs the truncated
  2148. // value.
  2149. if (OrigPhi == OldInduction) {
  2150. BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
  2151. OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
  2152. } else {
  2153. BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
  2154. OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
  2155. }
  2156. }
  2157. // If we are generating a new induction variable then we also need to
  2158. // generate the code that calculates the exit value. This value is not
  2159. // simply the end of the counter because we may skip the vectorized body
  2160. // in case of a runtime check.
  2161. if (!OldInduction){
  2162. assert(!ResumeIndex && "Unexpected resume value found");
  2163. ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
  2164. MiddleBlock->getTerminator());
  2165. for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
  2166. ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
  2167. ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
  2168. }
  2169. // Make sure that we found the index where scalar loop needs to continue.
  2170. assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
  2171. "Invalid resume Index");
  2172. // Add a check in the middle block to see if we have completed
  2173. // all of the iterations in the first vector loop.
  2174. // If (N - N%VF) == N, then we *don't* need to run the remainder.
  2175. Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
  2176. ResumeIndex, "cmp.n",
  2177. MiddleBlock->getTerminator());
  2178. BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
  2179. // Remove the old terminator.
  2180. MiddleBlock->getTerminator()->eraseFromParent();
  2181. // Create i+1 and fill the PHINode.
  2182. Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
  2183. Induction->addIncoming(StartIdx, VectorPH);
  2184. Induction->addIncoming(NextIdx, VecBody);
  2185. // Create the compare.
  2186. Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
  2187. Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
  2188. // Now we have two terminators. Remove the old one from the block.
  2189. VecBody->getTerminator()->eraseFromParent();
  2190. // Get ready to start creating new instructions into the vectorized body.
  2191. Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
  2192. // Save the state.
  2193. LoopVectorPreHeader = VectorPH;
  2194. LoopScalarPreHeader = ScalarPH;
  2195. LoopMiddleBlock = MiddleBlock;
  2196. LoopExitBlock = ExitBlock;
  2197. LoopVectorBody.push_back(VecBody);
  2198. LoopScalarBody = OldBasicBlock;
  2199. LoopVectorizeHints Hints(Lp, true);
  2200. Hints.setAlreadyVectorized();
  2201. }
  2202. /// This function returns the identity element (or neutral element) for
  2203. /// the operation K.
  2204. Constant*
  2205. LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
  2206. switch (K) {
  2207. case RK_IntegerXor:
  2208. case RK_IntegerAdd:
  2209. case RK_IntegerOr:
  2210. // Adding, Xoring, Oring zero to a number does not change it.
  2211. return ConstantInt::get(Tp, 0);
  2212. case RK_IntegerMult:
  2213. // Multiplying a number by 1 does not change it.
  2214. return ConstantInt::get(Tp, 1);
  2215. case RK_IntegerAnd:
  2216. // AND-ing a number with an all-1 value does not change it.
  2217. return ConstantInt::get(Tp, -1, true);
  2218. case RK_FloatMult:
  2219. // Multiplying a number by 1 does not change it.
  2220. return ConstantFP::get(Tp, 1.0L);
  2221. case RK_FloatAdd:
  2222. // Adding zero to a number does not change it.
  2223. return ConstantFP::get(Tp, 0.0L);
  2224. default:
  2225. llvm_unreachable("Unknown reduction kind");
  2226. }
  2227. }
  2228. /// This function translates the reduction kind to an LLVM binary operator.
  2229. static unsigned
  2230. getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
  2231. switch (Kind) {
  2232. case LoopVectorizationLegality::RK_IntegerAdd:
  2233. return Instruction::Add;
  2234. case LoopVectorizationLegality::RK_IntegerMult:
  2235. return Instruction::Mul;
  2236. case LoopVectorizationLegality::RK_IntegerOr:
  2237. return Instruction::Or;
  2238. case LoopVectorizationLegality::RK_IntegerAnd:
  2239. return Instruction::And;
  2240. case LoopVectorizationLegality::RK_IntegerXor:
  2241. return Instruction::Xor;
  2242. case LoopVectorizationLegality::RK_FloatMult:
  2243. return Instruction::FMul;
  2244. case LoopVectorizationLegality::RK_FloatAdd:
  2245. return Instruction::FAdd;
  2246. case LoopVectorizationLegality::RK_IntegerMinMax:
  2247. return Instruction::ICmp;
  2248. case LoopVectorizationLegality::RK_FloatMinMax:
  2249. return Instruction::FCmp;
  2250. default:
  2251. llvm_unreachable("Unknown reduction operation");
  2252. }
  2253. }
  2254. Value *createMinMaxOp(IRBuilder<> &Builder,
  2255. LoopVectorizationLegality::MinMaxReductionKind RK,
  2256. Value *Left,
  2257. Value *Right) {
  2258. CmpInst::Predicate P = CmpInst::ICMP_NE;
  2259. switch (RK) {
  2260. default:
  2261. llvm_unreachable("Unknown min/max reduction kind");
  2262. case LoopVectorizationLegality::MRK_UIntMin:
  2263. P = CmpInst::ICMP_ULT;
  2264. break;
  2265. case LoopVectorizationLegality::MRK_UIntMax:
  2266. P = CmpInst::ICMP_UGT;
  2267. break;
  2268. case LoopVectorizationLegality::MRK_SIntMin:
  2269. P = CmpInst::ICMP_SLT;
  2270. break;
  2271. case LoopVectorizationLegality::MRK_SIntMax:
  2272. P = CmpInst::ICMP_SGT;
  2273. break;
  2274. case LoopVectorizationLegality::MRK_FloatMin:
  2275. P = CmpInst::FCMP_OLT;
  2276. break;
  2277. case LoopVectorizationLegality::MRK_FloatMax:
  2278. P = CmpInst::FCMP_OGT;
  2279. break;
  2280. }
  2281. Value *Cmp;
  2282. if (RK == LoopVectorizationLegality::MRK_FloatMin ||
  2283. RK == LoopVectorizationLegality::MRK_FloatMax)
  2284. Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
  2285. else
  2286. Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
  2287. Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
  2288. return Select;
  2289. }
  2290. namespace {
  2291. struct CSEDenseMapInfo {
  2292. static bool canHandle(Instruction *I) {
  2293. return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
  2294. isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
  2295. }
  2296. static inline Instruction *getEmptyKey() {
  2297. return DenseMapInfo<Instruction *>::getEmptyKey();
  2298. }
  2299. static inline Instruction *getTombstoneKey() {
  2300. return DenseMapInfo<Instruction *>::getTombstoneKey();
  2301. }
  2302. static unsigned getHashValue(Instruction *I) {
  2303. assert(canHandle(I) && "Unknown instruction!");
  2304. return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
  2305. I->value_op_end()));
  2306. }
  2307. static bool isEqual(Instruction *LHS, Instruction *RHS) {
  2308. if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
  2309. LHS == getTombstoneKey() || RHS == getTombstoneKey())
  2310. return LHS == RHS;
  2311. return LHS->isIdenticalTo(RHS);
  2312. }
  2313. };
  2314. }
  2315. /// \brief Check whether this block is a predicated block.
  2316. /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
  2317. /// = ...; " blocks. We start with one vectorized basic block. For every
  2318. /// conditional block we split this vectorized block. Therefore, every second
  2319. /// block will be a predicated one.
  2320. static bool isPredicatedBlock(unsigned BlockNum) {
  2321. return BlockNum % 2;
  2322. }
  2323. ///\brief Perform cse of induction variable instructions.
  2324. static void cse(SmallVector<BasicBlock *, 4> &BBs) {
  2325. // Perform simple cse.
  2326. SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
  2327. for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
  2328. BasicBlock *BB = BBs[i];
  2329. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
  2330. Instruction *In = I++;
  2331. if (!CSEDenseMapInfo::canHandle(In))
  2332. continue;
  2333. // Check if we can replace this instruction with any of the
  2334. // visited instructions.
  2335. if (Instruction *V = CSEMap.lookup(In)) {
  2336. In->replaceAllUsesWith(V);
  2337. In->eraseFromParent();
  2338. continue;
  2339. }
  2340. // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
  2341. // ...;" blocks for predicated stores. Every second block is a predicated
  2342. // block.
  2343. if (isPredicatedBlock(i))
  2344. continue;
  2345. CSEMap[In] = In;
  2346. }
  2347. }
  2348. }
  2349. /// \brief Adds a 'fast' flag to floating point operations.
  2350. static Value *addFastMathFlag(Value *V) {
  2351. if (isa<FPMathOperator>(V)){
  2352. FastMathFlags Flags;
  2353. Flags.setUnsafeAlgebra();
  2354. cast<Instruction>(V)->setFastMathFlags(Flags);
  2355. }
  2356. return V;
  2357. }
  2358. void InnerLoopVectorizer::vectorizeLoop() {
  2359. //===------------------------------------------------===//
  2360. //
  2361. // Notice: any optimization or new instruction that go
  2362. // into the code below should be also be implemented in
  2363. // the cost-model.
  2364. //
  2365. //===------------------------------------------------===//
  2366. Constant *Zero = Builder.getInt32(0);
  2367. // In order to support reduction variables we need to be able to vectorize
  2368. // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
  2369. // stages. First, we create a new vector PHI node with no incoming edges.
  2370. // We use this value when we vectorize all of the instructions that use the
  2371. // PHI. Next, after all of the instructions in the block are complete we
  2372. // add the new incoming edges to the PHI. At this point all of the
  2373. // instructions in the basic block are vectorized, so we can use them to
  2374. // construct the PHI.
  2375. PhiVector RdxPHIsToFix;
  2376. // Scan the loop in a topological order to ensure that defs are vectorized
  2377. // before users.
  2378. LoopBlocksDFS DFS(OrigLoop);
  2379. DFS.perform(LI);
  2380. // Vectorize all of the blocks in the original loop.
  2381. for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
  2382. be = DFS.endRPO(); bb != be; ++bb)
  2383. vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
  2384. // At this point every instruction in the original loop is widened to
  2385. // a vector form. We are almost done. Now, we need to fix the PHI nodes
  2386. // that we vectorized. The PHI nodes are currently empty because we did
  2387. // not want to introduce cycles. Notice that the remaining PHI nodes
  2388. // that we need to fix are reduction variables.
  2389. // Create the 'reduced' values for each of the induction vars.
  2390. // The reduced values are the vector values that we scalarize and combine
  2391. // after the loop is finished.
  2392. for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
  2393. it != e; ++it) {
  2394. PHINode *RdxPhi = *it;
  2395. assert(RdxPhi && "Unable to recover vectorized PHI");
  2396. // Find the reduction variable descriptor.
  2397. assert(Legal->getReductionVars()->count(RdxPhi) &&
  2398. "Unable to find the reduction variable");
  2399. LoopVectorizationLegality::ReductionDescriptor RdxDesc =
  2400. (*Legal->getReductionVars())[RdxPhi];
  2401. setDebugLocFromInst(Builder, RdxDesc.StartValue);
  2402. // We need to generate a reduction vector from the incoming scalar.
  2403. // To do so, we need to generate the 'identity' vector and override
  2404. // one of the elements with the incoming scalar reduction. We need
  2405. // to do it in the vector-loop preheader.
  2406. Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
  2407. // This is the vector-clone of the value that leaves the loop.
  2408. VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
  2409. Type *VecTy = VectorExit[0]->getType();
  2410. // Find the reduction identity variable. Zero for addition, or, xor,
  2411. // one for multiplication, -1 for And.
  2412. Value *Identity;
  2413. Value *VectorStart;
  2414. if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
  2415. RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
  2416. // MinMax reduction have the start value as their identify.
  2417. if (VF == 1) {
  2418. VectorStart = Identity = RdxDesc.StartValue;
  2419. } else {
  2420. VectorStart = Identity = Builder.CreateVectorSplat(VF,
  2421. RdxDesc.StartValue,
  2422. "minmax.ident");
  2423. }
  2424. } else {
  2425. // Handle other reduction kinds:
  2426. Constant *Iden =
  2427. LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
  2428. VecTy->getScalarType());
  2429. if (VF == 1) {
  2430. Identity = Iden;
  2431. // This vector is the Identity vector where the first element is the
  2432. // incoming scalar reduction.
  2433. VectorStart = RdxDesc.StartValue;
  2434. } else {
  2435. Identity = ConstantVector::getSplat(VF, Iden);
  2436. // This vector is the Identity vector where the first element is the
  2437. // incoming scalar reduction.
  2438. VectorStart = Builder.CreateInsertElement(Identity,
  2439. RdxDesc.StartValue, Zero);
  2440. }
  2441. }
  2442. // Fix the vector-loop phi.
  2443. // We created the induction variable so we know that the
  2444. // preheader is the first entry.
  2445. BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
  2446. // Reductions do not have to start at zero. They can start with
  2447. // any loop invariant values.
  2448. VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
  2449. BasicBlock *Latch = OrigLoop->getLoopLatch();
  2450. Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
  2451. VectorParts &Val = getVectorValue(LoopVal);
  2452. for (unsigned part = 0; part < UF; ++part) {
  2453. // Make sure to add the reduction stat value only to the
  2454. // first unroll part.
  2455. Value *StartVal = (part == 0) ? VectorStart : Identity;
  2456. cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
  2457. cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
  2458. LoopVectorBody.back());
  2459. }
  2460. // Before each round, move the insertion point right between
  2461. // the PHIs and the values we are going to write.
  2462. // This allows us to write both PHINodes and the extractelement
  2463. // instructions.
  2464. Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
  2465. VectorParts RdxParts;
  2466. setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
  2467. for (unsigned part = 0; part < UF; ++part) {
  2468. // This PHINode contains the vectorized reduction variable, or
  2469. // the initial value vector, if we bypass the vector loop.
  2470. VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
  2471. PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
  2472. Value *StartVal = (part == 0) ? VectorStart : Identity;
  2473. for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
  2474. NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
  2475. NewPhi->addIncoming(RdxExitVal[part],
  2476. LoopVectorBody.back());
  2477. RdxParts.push_back(NewPhi);
  2478. }
  2479. // Reduce all of the unrolled parts into a single vector.
  2480. Value *ReducedPartRdx = RdxParts[0];
  2481. unsigned Op = getReductionBinOp(RdxDesc.Kind);
  2482. setDebugLocFromInst(Builder, ReducedPartRdx);
  2483. for (unsigned part = 1; part < UF; ++part) {
  2484. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  2485. // Floating point operations had to be 'fast' to enable the reduction.
  2486. ReducedPartRdx = addFastMathFlag(
  2487. Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
  2488. ReducedPartRdx, "bin.rdx"));
  2489. else
  2490. ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
  2491. ReducedPartRdx, RdxParts[part]);
  2492. }
  2493. if (VF > 1) {
  2494. // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
  2495. // and vector ops, reducing the set of values being computed by half each
  2496. // round.
  2497. assert(isPowerOf2_32(VF) &&
  2498. "Reduction emission only supported for pow2 vectors!");
  2499. Value *TmpVec = ReducedPartRdx;
  2500. SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
  2501. for (unsigned i = VF; i != 1; i >>= 1) {
  2502. // Move the upper half of the vector to the lower half.
  2503. for (unsigned j = 0; j != i/2; ++j)
  2504. ShuffleMask[j] = Builder.getInt32(i/2 + j);
  2505. // Fill the rest of the mask with undef.
  2506. std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
  2507. UndefValue::get(Builder.getInt32Ty()));
  2508. Value *Shuf =
  2509. Builder.CreateShuffleVector(TmpVec,
  2510. UndefValue::get(TmpVec->getType()),
  2511. ConstantVector::get(ShuffleMask),
  2512. "rdx.shuf");
  2513. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  2514. // Floating point operations had to be 'fast' to enable the reduction.
  2515. TmpVec = addFastMathFlag(Builder.CreateBinOp(
  2516. (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
  2517. else
  2518. TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
  2519. }
  2520. // The result is in the first element of the vector.
  2521. ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
  2522. Builder.getInt32(0));
  2523. }
  2524. // Create a phi node that merges control-flow from the backedge-taken check
  2525. // block and the middle block.
  2526. PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
  2527. LoopScalarPreHeader->getTerminator());
  2528. BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
  2529. BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
  2530. // Now, we need to fix the users of the reduction variable
  2531. // inside and outside of the scalar remainder loop.
  2532. // We know that the loop is in LCSSA form. We need to update the
  2533. // PHI nodes in the exit blocks.
  2534. for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
  2535. LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
  2536. PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
  2537. if (!LCSSAPhi) break;
  2538. // All PHINodes need to have a single entry edge, or two if
  2539. // we already fixed them.
  2540. assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
  2541. // We found our reduction value exit-PHI. Update it with the
  2542. // incoming bypass edge.
  2543. if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
  2544. // Add an edge coming from the bypass.
  2545. LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
  2546. break;
  2547. }
  2548. }// end of the LCSSA phi scan.
  2549. // Fix the scalar loop reduction variable with the incoming reduction sum
  2550. // from the vector body and from the backedge value.
  2551. int IncomingEdgeBlockIdx =
  2552. (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
  2553. assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
  2554. // Pick the other block.
  2555. int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
  2556. (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
  2557. (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
  2558. }// end of for each redux variable.
  2559. fixLCSSAPHIs();
  2560. // Remove redundant induction instructions.
  2561. cse(LoopVectorBody);
  2562. }
  2563. void InnerLoopVectorizer::fixLCSSAPHIs() {
  2564. for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
  2565. LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
  2566. PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
  2567. if (!LCSSAPhi) break;
  2568. if (LCSSAPhi->getNumIncomingValues() == 1)
  2569. LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
  2570. LoopMiddleBlock);
  2571. }
  2572. }
  2573. InnerLoopVectorizer::VectorParts
  2574. InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
  2575. assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
  2576. "Invalid edge");
  2577. // Look for cached value.
  2578. std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
  2579. EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
  2580. if (ECEntryIt != MaskCache.end())
  2581. return ECEntryIt->second;
  2582. VectorParts SrcMask = createBlockInMask(Src);
  2583. // The terminator has to be a branch inst!
  2584. BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
  2585. assert(BI && "Unexpected terminator found");
  2586. if (BI->isConditional()) {
  2587. VectorParts EdgeMask = getVectorValue(BI->getCondition());
  2588. if (BI->getSuccessor(0) != Dst)
  2589. for (unsigned part = 0; part < UF; ++part)
  2590. EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
  2591. for (unsigned part = 0; part < UF; ++part)
  2592. EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
  2593. MaskCache[Edge] = EdgeMask;
  2594. return EdgeMask;
  2595. }
  2596. MaskCache[Edge] = SrcMask;
  2597. return SrcMask;
  2598. }
  2599. InnerLoopVectorizer::VectorParts
  2600. InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
  2601. assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
  2602. // Loop incoming mask is all-one.
  2603. if (OrigLoop->getHeader() == BB) {
  2604. Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
  2605. return getVectorValue(C);
  2606. }
  2607. // This is the block mask. We OR all incoming edges, and with zero.
  2608. Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
  2609. VectorParts BlockMask = getVectorValue(Zero);
  2610. // For each pred:
  2611. for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
  2612. VectorParts EM = createEdgeMask(*it, BB);
  2613. for (unsigned part = 0; part < UF; ++part)
  2614. BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
  2615. }
  2616. return BlockMask;
  2617. }
  2618. void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
  2619. InnerLoopVectorizer::VectorParts &Entry,
  2620. unsigned UF, unsigned VF, PhiVector *PV) {
  2621. PHINode* P = cast<PHINode>(PN);
  2622. // Handle reduction variables:
  2623. if (Legal->getReductionVars()->count(P)) {
  2624. for (unsigned part = 0; part < UF; ++part) {
  2625. // This is phase one of vectorizing PHIs.
  2626. Type *VecTy = (VF == 1) ? PN->getType() :
  2627. VectorType::get(PN->getType(), VF);
  2628. Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
  2629. LoopVectorBody.back()-> getFirstInsertionPt());
  2630. }
  2631. PV->push_back(P);
  2632. return;
  2633. }
  2634. setDebugLocFromInst(Builder, P);
  2635. // Check for PHI nodes that are lowered to vector selects.
  2636. if (P->getParent() != OrigLoop->getHeader()) {
  2637. // We know that all PHIs in non-header blocks are converted into
  2638. // selects, so we don't have to worry about the insertion order and we
  2639. // can just use the builder.
  2640. // At this point we generate the predication tree. There may be
  2641. // duplications since this is a simple recursive scan, but future
  2642. // optimizations will clean it up.
  2643. unsigned NumIncoming = P->getNumIncomingValues();
  2644. // Generate a sequence of selects of the form:
  2645. // SELECT(Mask3, In3,
  2646. // SELECT(Mask2, In2,
  2647. // ( ...)))
  2648. for (unsigned In = 0; In < NumIncoming; In++) {
  2649. VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
  2650. P->getParent());
  2651. VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
  2652. for (unsigned part = 0; part < UF; ++part) {
  2653. // We might have single edge PHIs (blocks) - use an identity
  2654. // 'select' for the first PHI operand.
  2655. if (In == 0)
  2656. Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
  2657. In0[part]);
  2658. else
  2659. // Select between the current value and the previous incoming edge
  2660. // based on the incoming mask.
  2661. Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
  2662. Entry[part], "predphi");
  2663. }
  2664. }
  2665. return;
  2666. }
  2667. // This PHINode must be an induction variable.
  2668. // Make sure that we know about it.
  2669. assert(Legal->getInductionVars()->count(P) &&
  2670. "Not an induction variable");
  2671. LoopVectorizationLegality::InductionInfo II =
  2672. Legal->getInductionVars()->lookup(P);
  2673. switch (II.IK) {
  2674. case LoopVectorizationLegality::IK_NoInduction:
  2675. llvm_unreachable("Unknown induction");
  2676. case LoopVectorizationLegality::IK_IntInduction: {
  2677. assert(P->getType() == II.StartValue->getType() && "Types must match");
  2678. Type *PhiTy = P->getType();
  2679. Value *Broadcasted;
  2680. if (P == OldInduction) {
  2681. // Handle the canonical induction variable. We might have had to
  2682. // extend the type.
  2683. Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
  2684. } else {
  2685. // Handle other induction variables that are now based on the
  2686. // canonical one.
  2687. Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
  2688. "normalized.idx");
  2689. NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
  2690. Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
  2691. "offset.idx");
  2692. }
  2693. Broadcasted = getBroadcastInstrs(Broadcasted);
  2694. // After broadcasting the induction variable we need to make the vector
  2695. // consecutive by adding 0, 1, 2, etc.
  2696. for (unsigned part = 0; part < UF; ++part)
  2697. Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
  2698. return;
  2699. }
  2700. case LoopVectorizationLegality::IK_ReverseIntInduction:
  2701. case LoopVectorizationLegality::IK_PtrInduction:
  2702. case LoopVectorizationLegality::IK_ReversePtrInduction:
  2703. // Handle reverse integer and pointer inductions.
  2704. Value *StartIdx = ExtendedIdx;
  2705. // This is the normalized GEP that starts counting at zero.
  2706. Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
  2707. "normalized.idx");
  2708. // Handle the reverse integer induction variable case.
  2709. if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
  2710. IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
  2711. Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
  2712. "resize.norm.idx");
  2713. Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
  2714. "reverse.idx");
  2715. // This is a new value so do not hoist it out.
  2716. Value *Broadcasted = getBroadcastInstrs(ReverseInd);
  2717. // After broadcasting the induction variable we need to make the
  2718. // vector consecutive by adding ... -3, -2, -1, 0.
  2719. for (unsigned part = 0; part < UF; ++part)
  2720. Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
  2721. true);
  2722. return;
  2723. }
  2724. // Handle the pointer induction variable case.
  2725. assert(P->getType()->isPointerTy() && "Unexpected type.");
  2726. // Is this a reverse induction ptr or a consecutive induction ptr.
  2727. bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
  2728. II.IK);
  2729. // This is the vector of results. Notice that we don't generate
  2730. // vector geps because scalar geps result in better code.
  2731. for (unsigned part = 0; part < UF; ++part) {
  2732. if (VF == 1) {
  2733. int EltIndex = (part) * (Reverse ? -1 : 1);
  2734. Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
  2735. Value *GlobalIdx;
  2736. if (Reverse)
  2737. GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
  2738. else
  2739. GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
  2740. Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
  2741. "next.gep");
  2742. Entry[part] = SclrGep;
  2743. continue;
  2744. }
  2745. Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
  2746. for (unsigned int i = 0; i < VF; ++i) {
  2747. int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
  2748. Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
  2749. Value *GlobalIdx;
  2750. if (!Reverse)
  2751. GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
  2752. else
  2753. GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
  2754. Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
  2755. "next.gep");
  2756. VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
  2757. Builder.getInt32(i),
  2758. "insert.gep");
  2759. }
  2760. Entry[part] = VecVal;
  2761. }
  2762. return;
  2763. }
  2764. }
  2765. void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
  2766. // For each instruction in the old loop.
  2767. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  2768. VectorParts &Entry = WidenMap.get(it);
  2769. switch (it->getOpcode()) {
  2770. case Instruction::Br:
  2771. // Nothing to do for PHIs and BR, since we already took care of the
  2772. // loop control flow instructions.
  2773. continue;
  2774. case Instruction::PHI:{
  2775. // Vectorize PHINodes.
  2776. widenPHIInstruction(it, Entry, UF, VF, PV);
  2777. continue;
  2778. }// End of PHI.
  2779. case Instruction::Add:
  2780. case Instruction::FAdd:
  2781. case Instruction::Sub:
  2782. case Instruction::FSub:
  2783. case Instruction::Mul:
  2784. case Instruction::FMul:
  2785. case Instruction::UDiv:
  2786. case Instruction::SDiv:
  2787. case Instruction::FDiv:
  2788. case Instruction::URem:
  2789. case Instruction::SRem:
  2790. case Instruction::FRem:
  2791. case Instruction::Shl:
  2792. case Instruction::LShr:
  2793. case Instruction::AShr:
  2794. case Instruction::And:
  2795. case Instruction::Or:
  2796. case Instruction::Xor: {
  2797. // Just widen binops.
  2798. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
  2799. setDebugLocFromInst(Builder, BinOp);
  2800. VectorParts &A = getVectorValue(it->getOperand(0));
  2801. VectorParts &B = getVectorValue(it->getOperand(1));
  2802. // Use this vector value for all users of the original instruction.
  2803. for (unsigned Part = 0; Part < UF; ++Part) {
  2804. Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
  2805. if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
  2806. VecOp->copyIRFlags(BinOp);
  2807. Entry[Part] = V;
  2808. }
  2809. propagateMetadata(Entry, it);
  2810. break;
  2811. }
  2812. case Instruction::Select: {
  2813. // Widen selects.
  2814. // If the selector is loop invariant we can create a select
  2815. // instruction with a scalar condition. Otherwise, use vector-select.
  2816. bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
  2817. OrigLoop);
  2818. setDebugLocFromInst(Builder, it);
  2819. // The condition can be loop invariant but still defined inside the
  2820. // loop. This means that we can't just use the original 'cond' value.
  2821. // We have to take the 'vectorized' value and pick the first lane.
  2822. // Instcombine will make this a no-op.
  2823. VectorParts &Cond = getVectorValue(it->getOperand(0));
  2824. VectorParts &Op0 = getVectorValue(it->getOperand(1));
  2825. VectorParts &Op1 = getVectorValue(it->getOperand(2));
  2826. Value *ScalarCond = (VF == 1) ? Cond[0] :
  2827. Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
  2828. for (unsigned Part = 0; Part < UF; ++Part) {
  2829. Entry[Part] = Builder.CreateSelect(
  2830. InvariantCond ? ScalarCond : Cond[Part],
  2831. Op0[Part],
  2832. Op1[Part]);
  2833. }
  2834. propagateMetadata(Entry, it);
  2835. break;
  2836. }
  2837. case Instruction::ICmp:
  2838. case Instruction::FCmp: {
  2839. // Widen compares. Generate vector compares.
  2840. bool FCmp = (it->getOpcode() == Instruction::FCmp);
  2841. CmpInst *Cmp = dyn_cast<CmpInst>(it);
  2842. setDebugLocFromInst(Builder, it);
  2843. VectorParts &A = getVectorValue(it->getOperand(0));
  2844. VectorParts &B = getVectorValue(it->getOperand(1));
  2845. for (unsigned Part = 0; Part < UF; ++Part) {
  2846. Value *C = nullptr;
  2847. if (FCmp)
  2848. C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
  2849. else
  2850. C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
  2851. Entry[Part] = C;
  2852. }
  2853. propagateMetadata(Entry, it);
  2854. break;
  2855. }
  2856. case Instruction::Store:
  2857. case Instruction::Load:
  2858. vectorizeMemoryInstruction(it);
  2859. break;
  2860. case Instruction::ZExt:
  2861. case Instruction::SExt:
  2862. case Instruction::FPToUI:
  2863. case Instruction::FPToSI:
  2864. case Instruction::FPExt:
  2865. case Instruction::PtrToInt:
  2866. case Instruction::IntToPtr:
  2867. case Instruction::SIToFP:
  2868. case Instruction::UIToFP:
  2869. case Instruction::Trunc:
  2870. case Instruction::FPTrunc:
  2871. case Instruction::BitCast: {
  2872. CastInst *CI = dyn_cast<CastInst>(it);
  2873. setDebugLocFromInst(Builder, it);
  2874. /// Optimize the special case where the source is the induction
  2875. /// variable. Notice that we can only optimize the 'trunc' case
  2876. /// because: a. FP conversions lose precision, b. sext/zext may wrap,
  2877. /// c. other casts depend on pointer size.
  2878. if (CI->getOperand(0) == OldInduction &&
  2879. it->getOpcode() == Instruction::Trunc) {
  2880. Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
  2881. CI->getType());
  2882. Value *Broadcasted = getBroadcastInstrs(ScalarCast);
  2883. for (unsigned Part = 0; Part < UF; ++Part)
  2884. Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
  2885. propagateMetadata(Entry, it);
  2886. break;
  2887. }
  2888. /// Vectorize casts.
  2889. Type *DestTy = (VF == 1) ? CI->getType() :
  2890. VectorType::get(CI->getType(), VF);
  2891. VectorParts &A = getVectorValue(it->getOperand(0));
  2892. for (unsigned Part = 0; Part < UF; ++Part)
  2893. Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
  2894. propagateMetadata(Entry, it);
  2895. break;
  2896. }
  2897. case Instruction::Call: {
  2898. // Ignore dbg intrinsics.
  2899. if (isa<DbgInfoIntrinsic>(it))
  2900. break;
  2901. setDebugLocFromInst(Builder, it);
  2902. Module *M = BB->getParent()->getParent();
  2903. CallInst *CI = cast<CallInst>(it);
  2904. Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
  2905. assert(ID && "Not an intrinsic call!");
  2906. switch (ID) {
  2907. case Intrinsic::assume:
  2908. case Intrinsic::lifetime_end:
  2909. case Intrinsic::lifetime_start:
  2910. scalarizeInstruction(it);
  2911. break;
  2912. default:
  2913. bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
  2914. for (unsigned Part = 0; Part < UF; ++Part) {
  2915. SmallVector<Value *, 4> Args;
  2916. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
  2917. if (HasScalarOpd && i == 1) {
  2918. Args.push_back(CI->getArgOperand(i));
  2919. continue;
  2920. }
  2921. VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
  2922. Args.push_back(Arg[Part]);
  2923. }
  2924. Type *Tys[] = {CI->getType()};
  2925. if (VF > 1)
  2926. Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
  2927. Function *F = Intrinsic::getDeclaration(M, ID, Tys);
  2928. Entry[Part] = Builder.CreateCall(F, Args);
  2929. }
  2930. propagateMetadata(Entry, it);
  2931. break;
  2932. }
  2933. break;
  2934. }
  2935. default:
  2936. // All other instructions are unsupported. Scalarize them.
  2937. scalarizeInstruction(it);
  2938. break;
  2939. }// end of switch.
  2940. }// end of for_each instr.
  2941. }
  2942. void InnerLoopVectorizer::updateAnalysis() {
  2943. // Forget the original basic block.
  2944. SE->forgetLoop(OrigLoop);
  2945. // Update the dominator tree information.
  2946. assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
  2947. "Entry does not dominate exit.");
  2948. for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
  2949. DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
  2950. DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
  2951. // Due to if predication of stores we might create a sequence of "if(pred)
  2952. // a[i] = ...; " blocks.
  2953. for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
  2954. if (i == 0)
  2955. DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
  2956. else if (isPredicatedBlock(i)) {
  2957. DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
  2958. } else {
  2959. DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
  2960. }
  2961. }
  2962. DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
  2963. DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
  2964. DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
  2965. DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
  2966. DEBUG(DT->verifyDomTree());
  2967. }
  2968. /// \brief Check whether it is safe to if-convert this phi node.
  2969. ///
  2970. /// Phi nodes with constant expressions that can trap are not safe to if
  2971. /// convert.
  2972. static bool canIfConvertPHINodes(BasicBlock *BB) {
  2973. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  2974. PHINode *Phi = dyn_cast<PHINode>(I);
  2975. if (!Phi)
  2976. return true;
  2977. for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
  2978. if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
  2979. if (C->canTrap())
  2980. return false;
  2981. }
  2982. return true;
  2983. }
  2984. bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
  2985. if (!EnableIfConversion) {
  2986. emitAnalysis(Report() << "if-conversion is disabled");
  2987. return false;
  2988. }
  2989. assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
  2990. // A list of pointers that we can safely read and write to.
  2991. SmallPtrSet<Value *, 8> SafePointes;
  2992. // Collect safe addresses.
  2993. for (Loop::block_iterator BI = TheLoop->block_begin(),
  2994. BE = TheLoop->block_end(); BI != BE; ++BI) {
  2995. BasicBlock *BB = *BI;
  2996. if (blockNeedsPredication(BB))
  2997. continue;
  2998. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  2999. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  3000. SafePointes.insert(LI->getPointerOperand());
  3001. else if (StoreInst *SI = dyn_cast<StoreInst>(I))
  3002. SafePointes.insert(SI->getPointerOperand());
  3003. }
  3004. }
  3005. // Collect the blocks that need predication.
  3006. BasicBlock *Header = TheLoop->getHeader();
  3007. for (Loop::block_iterator BI = TheLoop->block_begin(),
  3008. BE = TheLoop->block_end(); BI != BE; ++BI) {
  3009. BasicBlock *BB = *BI;
  3010. // We don't support switch statements inside loops.
  3011. if (!isa<BranchInst>(BB->getTerminator())) {
  3012. emitAnalysis(Report(BB->getTerminator())
  3013. << "loop contains a switch statement");
  3014. return false;
  3015. }
  3016. // We must be able to predicate all blocks that need to be predicated.
  3017. if (blockNeedsPredication(BB)) {
  3018. if (!blockCanBePredicated(BB, SafePointes)) {
  3019. emitAnalysis(Report(BB->getTerminator())
  3020. << "control flow cannot be substituted for a select");
  3021. return false;
  3022. }
  3023. } else if (BB != Header && !canIfConvertPHINodes(BB)) {
  3024. emitAnalysis(Report(BB->getTerminator())
  3025. << "control flow cannot be substituted for a select");
  3026. return false;
  3027. }
  3028. }
  3029. // We can if-convert this loop.
  3030. return true;
  3031. }
  3032. bool LoopVectorizationLegality::canVectorize() {
  3033. // We must have a loop in canonical form. Loops with indirectbr in them cannot
  3034. // be canonicalized.
  3035. if (!TheLoop->getLoopPreheader()) {
  3036. emitAnalysis(
  3037. Report() << "loop control flow is not understood by vectorizer");
  3038. return false;
  3039. }
  3040. // We can only vectorize innermost loops.
  3041. if (TheLoop->getSubLoopsVector().size()) {
  3042. emitAnalysis(Report() << "loop is not the innermost loop");
  3043. return false;
  3044. }
  3045. // We must have a single backedge.
  3046. if (TheLoop->getNumBackEdges() != 1) {
  3047. emitAnalysis(
  3048. Report() << "loop control flow is not understood by vectorizer");
  3049. return false;
  3050. }
  3051. // We must have a single exiting block.
  3052. if (!TheLoop->getExitingBlock()) {
  3053. emitAnalysis(
  3054. Report() << "loop control flow is not understood by vectorizer");
  3055. return false;
  3056. }
  3057. // We only handle bottom-tested loops, i.e. loop in which the condition is
  3058. // checked at the end of each iteration. With that we can assume that all
  3059. // instructions in the loop are executed the same number of times.
  3060. if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
  3061. emitAnalysis(
  3062. Report() << "loop control flow is not understood by vectorizer");
  3063. return false;
  3064. }
  3065. // We need to have a loop header.
  3066. DEBUG(dbgs() << "LV: Found a loop: " <<
  3067. TheLoop->getHeader()->getName() << '\n');
  3068. // Check if we can if-convert non-single-bb loops.
  3069. unsigned NumBlocks = TheLoop->getNumBlocks();
  3070. if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
  3071. DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
  3072. return false;
  3073. }
  3074. // ScalarEvolution needs to be able to find the exit count.
  3075. const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
  3076. if (ExitCount == SE->getCouldNotCompute()) {
  3077. emitAnalysis(Report() << "could not determine number of loop iterations");
  3078. DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
  3079. return false;
  3080. }
  3081. // Check if we can vectorize the instructions and CFG in this loop.
  3082. if (!canVectorizeInstrs()) {
  3083. DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
  3084. return false;
  3085. }
  3086. // Go over each instruction and look at memory deps.
  3087. if (!canVectorizeMemory()) {
  3088. DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
  3089. return false;
  3090. }
  3091. // Collect all of the variables that remain uniform after vectorization.
  3092. collectLoopUniforms();
  3093. DEBUG(dbgs() << "LV: We can vectorize this loop" <<
  3094. (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
  3095. <<"!\n");
  3096. // Okay! We can vectorize. At this point we don't have any other mem analysis
  3097. // which may limit our maximum vectorization factor, so just return true with
  3098. // no restrictions.
  3099. return true;
  3100. }
  3101. static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
  3102. if (Ty->isPointerTy())
  3103. return DL.getIntPtrType(Ty);
  3104. // It is possible that char's or short's overflow when we ask for the loop's
  3105. // trip count, work around this by changing the type size.
  3106. if (Ty->getScalarSizeInBits() < 32)
  3107. return Type::getInt32Ty(Ty->getContext());
  3108. return Ty;
  3109. }
  3110. static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
  3111. Ty0 = convertPointerToIntegerType(DL, Ty0);
  3112. Ty1 = convertPointerToIntegerType(DL, Ty1);
  3113. if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
  3114. return Ty0;
  3115. return Ty1;
  3116. }
  3117. /// \brief Check that the instruction has outside loop users and is not an
  3118. /// identified reduction variable.
  3119. static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
  3120. SmallPtrSetImpl<Value *> &Reductions) {
  3121. // Reduction instructions are allowed to have exit users. All other
  3122. // instructions must not have external users.
  3123. if (!Reductions.count(Inst))
  3124. //Check that all of the users of the loop are inside the BB.
  3125. for (User *U : Inst->users()) {
  3126. Instruction *UI = cast<Instruction>(U);
  3127. // This user may be a reduction exit value.
  3128. if (!TheLoop->contains(UI)) {
  3129. DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
  3130. return true;
  3131. }
  3132. }
  3133. return false;
  3134. }
  3135. bool LoopVectorizationLegality::canVectorizeInstrs() {
  3136. BasicBlock *PreHeader = TheLoop->getLoopPreheader();
  3137. BasicBlock *Header = TheLoop->getHeader();
  3138. // Look for the attribute signaling the absence of NaNs.
  3139. Function &F = *Header->getParent();
  3140. if (F.hasFnAttribute("no-nans-fp-math"))
  3141. HasFunNoNaNAttr = F.getAttributes().getAttribute(
  3142. AttributeSet::FunctionIndex,
  3143. "no-nans-fp-math").getValueAsString() == "true";
  3144. // For each block in the loop.
  3145. for (Loop::block_iterator bb = TheLoop->block_begin(),
  3146. be = TheLoop->block_end(); bb != be; ++bb) {
  3147. // Scan the instructions in the block and look for hazards.
  3148. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  3149. ++it) {
  3150. if (PHINode *Phi = dyn_cast<PHINode>(it)) {
  3151. Type *PhiTy = Phi->getType();
  3152. // Check that this PHI type is allowed.
  3153. if (!PhiTy->isIntegerTy() &&
  3154. !PhiTy->isFloatingPointTy() &&
  3155. !PhiTy->isPointerTy()) {
  3156. emitAnalysis(Report(it)
  3157. << "loop control flow is not understood by vectorizer");
  3158. DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
  3159. return false;
  3160. }
  3161. // If this PHINode is not in the header block, then we know that we
  3162. // can convert it to select during if-conversion. No need to check if
  3163. // the PHIs in this block are induction or reduction variables.
  3164. if (*bb != Header) {
  3165. // Check that this instruction has no outside users or is an
  3166. // identified reduction value with an outside user.
  3167. if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
  3168. continue;
  3169. emitAnalysis(Report(it) << "value could not be identified as "
  3170. "an induction or reduction variable");
  3171. return false;
  3172. }
  3173. // We only allow if-converted PHIs with more than two incoming values.
  3174. if (Phi->getNumIncomingValues() != 2) {
  3175. emitAnalysis(Report(it)
  3176. << "control flow not understood by vectorizer");
  3177. DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
  3178. return false;
  3179. }
  3180. // This is the value coming from the preheader.
  3181. Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
  3182. // Check if this is an induction variable.
  3183. InductionKind IK = isInductionVariable(Phi);
  3184. if (IK_NoInduction != IK) {
  3185. // Get the widest type.
  3186. if (!WidestIndTy)
  3187. WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
  3188. else
  3189. WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
  3190. // Int inductions are special because we only allow one IV.
  3191. if (IK == IK_IntInduction) {
  3192. // Use the phi node with the widest type as induction. Use the last
  3193. // one if there are multiple (no good reason for doing this other
  3194. // than it is expedient).
  3195. if (!Induction || PhiTy == WidestIndTy)
  3196. Induction = Phi;
  3197. }
  3198. DEBUG(dbgs() << "LV: Found an induction variable.\n");
  3199. Inductions[Phi] = InductionInfo(StartValue, IK);
  3200. // Until we explicitly handle the case of an induction variable with
  3201. // an outside loop user we have to give up vectorizing this loop.
  3202. if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
  3203. emitAnalysis(Report(it) << "use of induction value outside of the "
  3204. "loop is not handled by vectorizer");
  3205. return false;
  3206. }
  3207. continue;
  3208. }
  3209. if (AddReductionVar(Phi, RK_IntegerAdd)) {
  3210. DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
  3211. continue;
  3212. }
  3213. if (AddReductionVar(Phi, RK_IntegerMult)) {
  3214. DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
  3215. continue;
  3216. }
  3217. if (AddReductionVar(Phi, RK_IntegerOr)) {
  3218. DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
  3219. continue;
  3220. }
  3221. if (AddReductionVar(Phi, RK_IntegerAnd)) {
  3222. DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
  3223. continue;
  3224. }
  3225. if (AddReductionVar(Phi, RK_IntegerXor)) {
  3226. DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
  3227. continue;
  3228. }
  3229. if (AddReductionVar(Phi, RK_IntegerMinMax)) {
  3230. DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
  3231. continue;
  3232. }
  3233. if (AddReductionVar(Phi, RK_FloatMult)) {
  3234. DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
  3235. continue;
  3236. }
  3237. if (AddReductionVar(Phi, RK_FloatAdd)) {
  3238. DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
  3239. continue;
  3240. }
  3241. if (AddReductionVar(Phi, RK_FloatMinMax)) {
  3242. DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
  3243. "\n");
  3244. continue;
  3245. }
  3246. emitAnalysis(Report(it) << "value that could not be identified as "
  3247. "reduction is used outside the loop");
  3248. DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
  3249. return false;
  3250. }// end of PHI handling
  3251. // We still don't handle functions. However, we can ignore dbg intrinsic
  3252. // calls and we do handle certain intrinsic and libm functions.
  3253. CallInst *CI = dyn_cast<CallInst>(it);
  3254. if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
  3255. emitAnalysis(Report(it) << "call instruction cannot be vectorized");
  3256. DEBUG(dbgs() << "LV: Found a call site.\n");
  3257. return false;
  3258. }
  3259. // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
  3260. // second argument is the same (i.e. loop invariant)
  3261. if (CI &&
  3262. hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
  3263. if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
  3264. emitAnalysis(Report(it)
  3265. << "intrinsic instruction cannot be vectorized");
  3266. DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
  3267. return false;
  3268. }
  3269. }
  3270. // Check that the instruction return type is vectorizable.
  3271. // Also, we can't vectorize extractelement instructions.
  3272. if ((!VectorType::isValidElementType(it->getType()) &&
  3273. !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
  3274. emitAnalysis(Report(it)
  3275. << "instruction return type cannot be vectorized");
  3276. DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
  3277. return false;
  3278. }
  3279. // Check that the stored type is vectorizable.
  3280. if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
  3281. Type *T = ST->getValueOperand()->getType();
  3282. if (!VectorType::isValidElementType(T)) {
  3283. emitAnalysis(Report(ST) << "store instruction cannot be vectorized");
  3284. return false;
  3285. }
  3286. if (EnableMemAccessVersioning)
  3287. collectStridedAcccess(ST);
  3288. }
  3289. if (EnableMemAccessVersioning)
  3290. if (LoadInst *LI = dyn_cast<LoadInst>(it))
  3291. collectStridedAcccess(LI);
  3292. // Reduction instructions are allowed to have exit users.
  3293. // All other instructions must not have external users.
  3294. if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
  3295. emitAnalysis(Report(it) << "value cannot be used outside the loop");
  3296. return false;
  3297. }
  3298. } // next instr.
  3299. }
  3300. if (!Induction) {
  3301. DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
  3302. if (Inductions.empty()) {
  3303. emitAnalysis(Report()
  3304. << "loop induction variable could not be identified");
  3305. return false;
  3306. }
  3307. }
  3308. return true;
  3309. }
  3310. ///\brief Remove GEPs whose indices but the last one are loop invariant and
  3311. /// return the induction operand of the gep pointer.
  3312. static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
  3313. const DataLayout *DL, Loop *Lp) {
  3314. GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3315. if (!GEP)
  3316. return Ptr;
  3317. unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
  3318. // Check that all of the gep indices are uniform except for our induction
  3319. // operand.
  3320. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
  3321. if (i != InductionOperand &&
  3322. !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
  3323. return Ptr;
  3324. return GEP->getOperand(InductionOperand);
  3325. }
  3326. ///\brief Look for a cast use of the passed value.
  3327. static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
  3328. Value *UniqueCast = nullptr;
  3329. for (User *U : Ptr->users()) {
  3330. CastInst *CI = dyn_cast<CastInst>(U);
  3331. if (CI && CI->getType() == Ty) {
  3332. if (!UniqueCast)
  3333. UniqueCast = CI;
  3334. else
  3335. return nullptr;
  3336. }
  3337. }
  3338. return UniqueCast;
  3339. }
  3340. ///\brief Get the stride of a pointer access in a loop.
  3341. /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
  3342. /// pointer to the Value, or null otherwise.
  3343. static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
  3344. const DataLayout *DL, Loop *Lp) {
  3345. const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
  3346. if (!PtrTy || PtrTy->isAggregateType())
  3347. return nullptr;
  3348. // Try to remove a gep instruction to make the pointer (actually index at this
  3349. // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
  3350. // pointer, otherwise, we are analyzing the index.
  3351. Value *OrigPtr = Ptr;
  3352. // The size of the pointer access.
  3353. int64_t PtrAccessSize = 1;
  3354. Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
  3355. const SCEV *V = SE->getSCEV(Ptr);
  3356. if (Ptr != OrigPtr)
  3357. // Strip off casts.
  3358. while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
  3359. V = C->getOperand();
  3360. const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
  3361. if (!S)
  3362. return nullptr;
  3363. V = S->getStepRecurrence(*SE);
  3364. if (!V)
  3365. return nullptr;
  3366. // Strip off the size of access multiplication if we are still analyzing the
  3367. // pointer.
  3368. if (OrigPtr == Ptr) {
  3369. DL->getTypeAllocSize(PtrTy->getElementType());
  3370. if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
  3371. if (M->getOperand(0)->getSCEVType() != scConstant)
  3372. return nullptr;
  3373. const APInt &APStepVal =
  3374. cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
  3375. // Huge step value - give up.
  3376. if (APStepVal.getBitWidth() > 64)
  3377. return nullptr;
  3378. int64_t StepVal = APStepVal.getSExtValue();
  3379. if (PtrAccessSize != StepVal)
  3380. return nullptr;
  3381. V = M->getOperand(1);
  3382. }
  3383. }
  3384. // Strip off casts.
  3385. Type *StripedOffRecurrenceCast = nullptr;
  3386. if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
  3387. StripedOffRecurrenceCast = C->getType();
  3388. V = C->getOperand();
  3389. }
  3390. // Look for the loop invariant symbolic value.
  3391. const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
  3392. if (!U)
  3393. return nullptr;
  3394. Value *Stride = U->getValue();
  3395. if (!Lp->isLoopInvariant(Stride))
  3396. return nullptr;
  3397. // If we have stripped off the recurrence cast we have to make sure that we
  3398. // return the value that is used in this loop so that we can replace it later.
  3399. if (StripedOffRecurrenceCast)
  3400. Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
  3401. return Stride;
  3402. }
  3403. void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
  3404. Value *Ptr = nullptr;
  3405. if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
  3406. Ptr = LI->getPointerOperand();
  3407. else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
  3408. Ptr = SI->getPointerOperand();
  3409. else
  3410. return;
  3411. Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
  3412. if (!Stride)
  3413. return;
  3414. DEBUG(dbgs() << "LV: Found a strided access that we can version");
  3415. DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
  3416. Strides[Ptr] = Stride;
  3417. StrideSet.insert(Stride);
  3418. }
  3419. void LoopVectorizationLegality::collectLoopUniforms() {
  3420. // We now know that the loop is vectorizable!
  3421. // Collect variables that will remain uniform after vectorization.
  3422. std::vector<Value*> Worklist;
  3423. BasicBlock *Latch = TheLoop->getLoopLatch();
  3424. // Start with the conditional branch and walk up the block.
  3425. Worklist.push_back(Latch->getTerminator()->getOperand(0));
  3426. // Also add all consecutive pointer values; these values will be uniform
  3427. // after vectorization (and subsequent cleanup) and, until revectorization is
  3428. // supported, all dependencies must also be uniform.
  3429. for (Loop::block_iterator B = TheLoop->block_begin(),
  3430. BE = TheLoop->block_end(); B != BE; ++B)
  3431. for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
  3432. I != IE; ++I)
  3433. if (I->getType()->isPointerTy() && isConsecutivePtr(I))
  3434. Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
  3435. while (Worklist.size()) {
  3436. Instruction *I = dyn_cast<Instruction>(Worklist.back());
  3437. Worklist.pop_back();
  3438. // Look at instructions inside this loop.
  3439. // Stop when reaching PHI nodes.
  3440. // TODO: we need to follow values all over the loop, not only in this block.
  3441. if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
  3442. continue;
  3443. // This is a known uniform.
  3444. Uniforms.insert(I);
  3445. // Insert all operands.
  3446. Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
  3447. }
  3448. }
  3449. namespace {
  3450. /// \brief Analyses memory accesses in a loop.
  3451. ///
  3452. /// Checks whether run time pointer checks are needed and builds sets for data
  3453. /// dependence checking.
  3454. class AccessAnalysis {
  3455. public:
  3456. /// \brief Read or write access location.
  3457. typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
  3458. typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
  3459. /// \brief Set of potential dependent memory accesses.
  3460. typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
  3461. AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
  3462. DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
  3463. /// \brief Register a load and whether it is only read from.
  3464. void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
  3465. Value *Ptr = const_cast<Value*>(Loc.Ptr);
  3466. AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
  3467. Accesses.insert(MemAccessInfo(Ptr, false));
  3468. if (IsReadOnly)
  3469. ReadOnlyPtr.insert(Ptr);
  3470. }
  3471. /// \brief Register a store.
  3472. void addStore(AliasAnalysis::Location &Loc) {
  3473. Value *Ptr = const_cast<Value*>(Loc.Ptr);
  3474. AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
  3475. Accesses.insert(MemAccessInfo(Ptr, true));
  3476. }
  3477. /// \brief Check whether we can check the pointers at runtime for
  3478. /// non-intersection.
  3479. bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
  3480. unsigned &NumComparisons, ScalarEvolution *SE,
  3481. Loop *TheLoop, ValueToValueMap &Strides,
  3482. bool ShouldCheckStride = false);
  3483. /// \brief Goes over all memory accesses, checks whether a RT check is needed
  3484. /// and builds sets of dependent accesses.
  3485. void buildDependenceSets() {
  3486. processMemAccesses();
  3487. }
  3488. bool isRTCheckNeeded() { return IsRTCheckNeeded; }
  3489. bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
  3490. void resetDepChecks() { CheckDeps.clear(); }
  3491. MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
  3492. private:
  3493. typedef SetVector<MemAccessInfo> PtrAccessSet;
  3494. /// \brief Go over all memory access and check whether runtime pointer checks
  3495. /// are needed /// and build sets of dependency check candidates.
  3496. void processMemAccesses();
  3497. /// Set of all accesses.
  3498. PtrAccessSet Accesses;
  3499. /// Set of accesses that need a further dependence check.
  3500. MemAccessInfoSet CheckDeps;
  3501. /// Set of pointers that are read only.
  3502. SmallPtrSet<Value*, 16> ReadOnlyPtr;
  3503. const DataLayout *DL;
  3504. /// An alias set tracker to partition the access set by underlying object and
  3505. //intrinsic property (such as TBAA metadata).
  3506. AliasSetTracker AST;
  3507. /// Sets of potentially dependent accesses - members of one set share an
  3508. /// underlying pointer. The set "CheckDeps" identfies which sets really need a
  3509. /// dependence check.
  3510. DepCandidates &DepCands;
  3511. bool IsRTCheckNeeded;
  3512. };
  3513. } // end anonymous namespace
  3514. /// \brief Check whether a pointer can participate in a runtime bounds check.
  3515. static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
  3516. Value *Ptr) {
  3517. const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
  3518. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
  3519. if (!AR)
  3520. return false;
  3521. return AR->isAffine();
  3522. }
  3523. /// \brief Check the stride of the pointer and ensure that it does not wrap in
  3524. /// the address space.
  3525. static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
  3526. const Loop *Lp, ValueToValueMap &StridesMap);
  3527. bool AccessAnalysis::canCheckPtrAtRT(
  3528. LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
  3529. unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
  3530. ValueToValueMap &StridesMap, bool ShouldCheckStride) {
  3531. // Find pointers with computable bounds. We are going to use this information
  3532. // to place a runtime bound check.
  3533. bool CanDoRT = true;
  3534. bool IsDepCheckNeeded = isDependencyCheckNeeded();
  3535. NumComparisons = 0;
  3536. // We assign a consecutive id to access from different alias sets.
  3537. // Accesses between different groups doesn't need to be checked.
  3538. unsigned ASId = 1;
  3539. for (auto &AS : AST) {
  3540. unsigned NumReadPtrChecks = 0;
  3541. unsigned NumWritePtrChecks = 0;
  3542. // We assign consecutive id to access from different dependence sets.
  3543. // Accesses within the same set don't need a runtime check.
  3544. unsigned RunningDepId = 1;
  3545. DenseMap<Value *, unsigned> DepSetId;
  3546. for (auto A : AS) {
  3547. Value *Ptr = A.getValue();
  3548. bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
  3549. MemAccessInfo Access(Ptr, IsWrite);
  3550. if (IsWrite)
  3551. ++NumWritePtrChecks;
  3552. else
  3553. ++NumReadPtrChecks;
  3554. if (hasComputableBounds(SE, StridesMap, Ptr) &&
  3555. // When we run after a failing dependency check we have to make sure we
  3556. // don't have wrapping pointers.
  3557. (!ShouldCheckStride ||
  3558. isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
  3559. // The id of the dependence set.
  3560. unsigned DepId;
  3561. if (IsDepCheckNeeded) {
  3562. Value *Leader = DepCands.getLeaderValue(Access).getPointer();
  3563. unsigned &LeaderId = DepSetId[Leader];
  3564. if (!LeaderId)
  3565. LeaderId = RunningDepId++;
  3566. DepId = LeaderId;
  3567. } else
  3568. // Each access has its own dependence set.
  3569. DepId = RunningDepId++;
  3570. RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
  3571. DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
  3572. } else {
  3573. CanDoRT = false;
  3574. }
  3575. }
  3576. if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
  3577. NumComparisons += 0; // Only one dependence set.
  3578. else {
  3579. NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
  3580. NumWritePtrChecks - 1));
  3581. }
  3582. ++ASId;
  3583. }
  3584. // If the pointers that we would use for the bounds comparison have different
  3585. // address spaces, assume the values aren't directly comparable, so we can't
  3586. // use them for the runtime check. We also have to assume they could
  3587. // overlap. In the future there should be metadata for whether address spaces
  3588. // are disjoint.
  3589. unsigned NumPointers = RtCheck.Pointers.size();
  3590. for (unsigned i = 0; i < NumPointers; ++i) {
  3591. for (unsigned j = i + 1; j < NumPointers; ++j) {
  3592. // Only need to check pointers between two different dependency sets.
  3593. if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
  3594. continue;
  3595. // Only need to check pointers in the same alias set.
  3596. if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
  3597. continue;
  3598. Value *PtrI = RtCheck.Pointers[i];
  3599. Value *PtrJ = RtCheck.Pointers[j];
  3600. unsigned ASi = PtrI->getType()->getPointerAddressSpace();
  3601. unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
  3602. if (ASi != ASj) {
  3603. DEBUG(dbgs() << "LV: Runtime check would require comparison between"
  3604. " different address spaces\n");
  3605. return false;
  3606. }
  3607. }
  3608. }
  3609. return CanDoRT;
  3610. }
  3611. void AccessAnalysis::processMemAccesses() {
  3612. // We process the set twice: first we process read-write pointers, last we
  3613. // process read-only pointers. This allows us to skip dependence tests for
  3614. // read-only pointers.
  3615. DEBUG(dbgs() << "LV: Processing memory accesses...\n");
  3616. DEBUG(dbgs() << " AST: "; AST.dump());
  3617. DEBUG(dbgs() << "LV: Accesses:\n");
  3618. DEBUG({
  3619. for (auto A : Accesses)
  3620. dbgs() << "\t" << *A.getPointer() << " (" <<
  3621. (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
  3622. "read-only" : "read")) << ")\n";
  3623. });
  3624. // The AliasSetTracker has nicely partitioned our pointers by metadata
  3625. // compatibility and potential for underlying-object overlap. As a result, we
  3626. // only need to check for potential pointer dependencies within each alias
  3627. // set.
  3628. for (auto &AS : AST) {
  3629. // Note that both the alias-set tracker and the alias sets themselves used
  3630. // linked lists internally and so the iteration order here is deterministic
  3631. // (matching the original instruction order within each set).
  3632. bool SetHasWrite = false;
  3633. // Map of pointers to last access encountered.
  3634. typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
  3635. UnderlyingObjToAccessMap ObjToLastAccess;
  3636. // Set of access to check after all writes have been processed.
  3637. PtrAccessSet DeferredAccesses;
  3638. // Iterate over each alias set twice, once to process read/write pointers,
  3639. // and then to process read-only pointers.
  3640. for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
  3641. bool UseDeferred = SetIteration > 0;
  3642. PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
  3643. for (auto A : AS) {
  3644. Value *Ptr = A.getValue();
  3645. bool IsWrite = S.count(MemAccessInfo(Ptr, true));
  3646. // If we're using the deferred access set, then it contains only reads.
  3647. bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
  3648. if (UseDeferred && !IsReadOnlyPtr)
  3649. continue;
  3650. // Otherwise, the pointer must be in the PtrAccessSet, either as a read
  3651. // or a write.
  3652. assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
  3653. S.count(MemAccessInfo(Ptr, false))) &&
  3654. "Alias-set pointer not in the access set?");
  3655. MemAccessInfo Access(Ptr, IsWrite);
  3656. DepCands.insert(Access);
  3657. // Memorize read-only pointers for later processing and skip them in the
  3658. // first round (they need to be checked after we have seen all write
  3659. // pointers). Note: we also mark pointer that are not consecutive as
  3660. // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need
  3661. // the second check for "!IsWrite".
  3662. if (!UseDeferred && IsReadOnlyPtr) {
  3663. DeferredAccesses.insert(Access);
  3664. continue;
  3665. }
  3666. // If this is a write - check other reads and writes for conflicts. If
  3667. // this is a read only check other writes for conflicts (but only if
  3668. // there is no other write to the ptr - this is an optimization to
  3669. // catch "a[i] = a[i] + " without having to do a dependence check).
  3670. if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
  3671. CheckDeps.insert(Access);
  3672. IsRTCheckNeeded = true;
  3673. }
  3674. if (IsWrite)
  3675. SetHasWrite = true;
  3676. // Create sets of pointers connected by a shared alias set and
  3677. // underlying object.
  3678. typedef SmallVector<Value *, 16> ValueVector;
  3679. ValueVector TempObjects;
  3680. GetUnderlyingObjects(Ptr, TempObjects, DL);
  3681. for (Value *UnderlyingObj : TempObjects) {
  3682. UnderlyingObjToAccessMap::iterator Prev =
  3683. ObjToLastAccess.find(UnderlyingObj);
  3684. if (Prev != ObjToLastAccess.end())
  3685. DepCands.unionSets(Access, Prev->second);
  3686. ObjToLastAccess[UnderlyingObj] = Access;
  3687. }
  3688. }
  3689. }
  3690. }
  3691. }
  3692. namespace {
  3693. /// \brief Checks memory dependences among accesses to the same underlying
  3694. /// object to determine whether there vectorization is legal or not (and at
  3695. /// which vectorization factor).
  3696. ///
  3697. /// This class works under the assumption that we already checked that memory
  3698. /// locations with different underlying pointers are "must-not alias".
  3699. /// We use the ScalarEvolution framework to symbolically evalutate access
  3700. /// functions pairs. Since we currently don't restructure the loop we can rely
  3701. /// on the program order of memory accesses to determine their safety.
  3702. /// At the moment we will only deem accesses as safe for:
  3703. /// * A negative constant distance assuming program order.
  3704. ///
  3705. /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
  3706. /// a[i] = tmp; y = a[i];
  3707. ///
  3708. /// The latter case is safe because later checks guarantuee that there can't
  3709. /// be a cycle through a phi node (that is, we check that "x" and "y" is not
  3710. /// the same variable: a header phi can only be an induction or a reduction, a
  3711. /// reduction can't have a memory sink, an induction can't have a memory
  3712. /// source). This is important and must not be violated (or we have to
  3713. /// resort to checking for cycles through memory).
  3714. ///
  3715. /// * A positive constant distance assuming program order that is bigger
  3716. /// than the biggest memory access.
  3717. ///
  3718. /// tmp = a[i] OR b[i] = x
  3719. /// a[i+2] = tmp y = b[i+2];
  3720. ///
  3721. /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
  3722. ///
  3723. /// * Zero distances and all accesses have the same size.
  3724. ///
  3725. class MemoryDepChecker {
  3726. public:
  3727. typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
  3728. typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
  3729. MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
  3730. : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
  3731. ShouldRetryWithRuntimeCheck(false) {}
  3732. /// \brief Register the location (instructions are given increasing numbers)
  3733. /// of a write access.
  3734. void addAccess(StoreInst *SI) {
  3735. Value *Ptr = SI->getPointerOperand();
  3736. Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
  3737. InstMap.push_back(SI);
  3738. ++AccessIdx;
  3739. }
  3740. /// \brief Register the location (instructions are given increasing numbers)
  3741. /// of a write access.
  3742. void addAccess(LoadInst *LI) {
  3743. Value *Ptr = LI->getPointerOperand();
  3744. Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
  3745. InstMap.push_back(LI);
  3746. ++AccessIdx;
  3747. }
  3748. /// \brief Check whether the dependencies between the accesses are safe.
  3749. ///
  3750. /// Only checks sets with elements in \p CheckDeps.
  3751. bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
  3752. MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
  3753. /// \brief The maximum number of bytes of a vector register we can vectorize
  3754. /// the accesses safely with.
  3755. unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
  3756. /// \brief In same cases when the dependency check fails we can still
  3757. /// vectorize the loop with a dynamic array access check.
  3758. bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
  3759. private:
  3760. ScalarEvolution *SE;
  3761. const DataLayout *DL;
  3762. const Loop *InnermostLoop;
  3763. /// \brief Maps access locations (ptr, read/write) to program order.
  3764. DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
  3765. /// \brief Memory access instructions in program order.
  3766. SmallVector<Instruction *, 16> InstMap;
  3767. /// \brief The program order index to be used for the next instruction.
  3768. unsigned AccessIdx;
  3769. // We can access this many bytes in parallel safely.
  3770. unsigned MaxSafeDepDistBytes;
  3771. /// \brief If we see a non-constant dependence distance we can still try to
  3772. /// vectorize this loop with runtime checks.
  3773. bool ShouldRetryWithRuntimeCheck;
  3774. /// \brief Check whether there is a plausible dependence between the two
  3775. /// accesses.
  3776. ///
  3777. /// Access \p A must happen before \p B in program order. The two indices
  3778. /// identify the index into the program order map.
  3779. ///
  3780. /// This function checks whether there is a plausible dependence (or the
  3781. /// absence of such can't be proved) between the two accesses. If there is a
  3782. /// plausible dependence but the dependence distance is bigger than one
  3783. /// element access it records this distance in \p MaxSafeDepDistBytes (if this
  3784. /// distance is smaller than any other distance encountered so far).
  3785. /// Otherwise, this function returns true signaling a possible dependence.
  3786. bool isDependent(const MemAccessInfo &A, unsigned AIdx,
  3787. const MemAccessInfo &B, unsigned BIdx,
  3788. ValueToValueMap &Strides);
  3789. /// \brief Check whether the data dependence could prevent store-load
  3790. /// forwarding.
  3791. bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
  3792. };
  3793. } // end anonymous namespace
  3794. static bool isInBoundsGep(Value *Ptr) {
  3795. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
  3796. return GEP->isInBounds();
  3797. return false;
  3798. }
  3799. /// \brief Check whether the access through \p Ptr has a constant stride.
  3800. static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
  3801. const Loop *Lp, ValueToValueMap &StridesMap) {
  3802. const Type *Ty = Ptr->getType();
  3803. assert(Ty->isPointerTy() && "Unexpected non-ptr");
  3804. // Make sure that the pointer does not point to aggregate types.
  3805. const PointerType *PtrTy = cast<PointerType>(Ty);
  3806. if (PtrTy->getElementType()->isAggregateType()) {
  3807. DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
  3808. "\n");
  3809. return 0;
  3810. }
  3811. const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
  3812. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
  3813. if (!AR) {
  3814. DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
  3815. << *Ptr << " SCEV: " << *PtrScev << "\n");
  3816. return 0;
  3817. }
  3818. // The accesss function must stride over the innermost loop.
  3819. if (Lp != AR->getLoop()) {
  3820. DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
  3821. *Ptr << " SCEV: " << *PtrScev << "\n");
  3822. }
  3823. // The address calculation must not wrap. Otherwise, a dependence could be
  3824. // inverted.
  3825. // An inbounds getelementptr that is a AddRec with a unit stride
  3826. // cannot wrap per definition. The unit stride requirement is checked later.
  3827. // An getelementptr without an inbounds attribute and unit stride would have
  3828. // to access the pointer value "0" which is undefined behavior in address
  3829. // space 0, therefore we can also vectorize this case.
  3830. bool IsInBoundsGEP = isInBoundsGep(Ptr);
  3831. bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
  3832. bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
  3833. if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
  3834. DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
  3835. << *Ptr << " SCEV: " << *PtrScev << "\n");
  3836. return 0;
  3837. }
  3838. // Check the step is constant.
  3839. const SCEV *Step = AR->getStepRecurrence(*SE);
  3840. // Calculate the pointer stride and check if it is consecutive.
  3841. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  3842. if (!C) {
  3843. DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
  3844. " SCEV: " << *PtrScev << "\n");
  3845. return 0;
  3846. }
  3847. int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
  3848. const APInt &APStepVal = C->getValue()->getValue();
  3849. // Huge step value - give up.
  3850. if (APStepVal.getBitWidth() > 64)
  3851. return 0;
  3852. int64_t StepVal = APStepVal.getSExtValue();
  3853. // Strided access.
  3854. int64_t Stride = StepVal / Size;
  3855. int64_t Rem = StepVal % Size;
  3856. if (Rem)
  3857. return 0;
  3858. // If the SCEV could wrap but we have an inbounds gep with a unit stride we
  3859. // know we can't "wrap around the address space". In case of address space
  3860. // zero we know that this won't happen without triggering undefined behavior.
  3861. if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
  3862. Stride != 1 && Stride != -1)
  3863. return 0;
  3864. return Stride;
  3865. }
  3866. bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
  3867. unsigned TypeByteSize) {
  3868. // If loads occur at a distance that is not a multiple of a feasible vector
  3869. // factor store-load forwarding does not take place.
  3870. // Positive dependences might cause troubles because vectorizing them might
  3871. // prevent store-load forwarding making vectorized code run a lot slower.
  3872. // a[i] = a[i-3] ^ a[i-8];
  3873. // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
  3874. // hence on your typical architecture store-load forwarding does not take
  3875. // place. Vectorizing in such cases does not make sense.
  3876. // Store-load forwarding distance.
  3877. const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
  3878. // Maximum vector factor.
  3879. unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
  3880. if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
  3881. MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
  3882. for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
  3883. vf *= 2) {
  3884. if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
  3885. MaxVFWithoutSLForwardIssues = (vf >>=1);
  3886. break;
  3887. }
  3888. }
  3889. if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
  3890. DEBUG(dbgs() << "LV: Distance " << Distance <<
  3891. " that could cause a store-load forwarding conflict\n");
  3892. return true;
  3893. }
  3894. if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
  3895. MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
  3896. MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
  3897. return false;
  3898. }
  3899. bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
  3900. const MemAccessInfo &B, unsigned BIdx,
  3901. ValueToValueMap &Strides) {
  3902. assert (AIdx < BIdx && "Must pass arguments in program order");
  3903. Value *APtr = A.getPointer();
  3904. Value *BPtr = B.getPointer();
  3905. bool AIsWrite = A.getInt();
  3906. bool BIsWrite = B.getInt();
  3907. // Two reads are independent.
  3908. if (!AIsWrite && !BIsWrite)
  3909. return false;
  3910. // We cannot check pointers in different address spaces.
  3911. if (APtr->getType()->getPointerAddressSpace() !=
  3912. BPtr->getType()->getPointerAddressSpace())
  3913. return true;
  3914. const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
  3915. const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
  3916. int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
  3917. int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
  3918. const SCEV *Src = AScev;
  3919. const SCEV *Sink = BScev;
  3920. // If the induction step is negative we have to invert source and sink of the
  3921. // dependence.
  3922. if (StrideAPtr < 0) {
  3923. //Src = BScev;
  3924. //Sink = AScev;
  3925. std::swap(APtr, BPtr);
  3926. std::swap(Src, Sink);
  3927. std::swap(AIsWrite, BIsWrite);
  3928. std::swap(AIdx, BIdx);
  3929. std::swap(StrideAPtr, StrideBPtr);
  3930. }
  3931. const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
  3932. DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
  3933. << "(Induction step: " << StrideAPtr << ")\n");
  3934. DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
  3935. << *InstMap[BIdx] << ": " << *Dist << "\n");
  3936. // Need consecutive accesses. We don't want to vectorize
  3937. // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
  3938. // the address space.
  3939. if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
  3940. DEBUG(dbgs() << "Non-consecutive pointer access\n");
  3941. return true;
  3942. }
  3943. const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
  3944. if (!C) {
  3945. DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
  3946. ShouldRetryWithRuntimeCheck = true;
  3947. return true;
  3948. }
  3949. Type *ATy = APtr->getType()->getPointerElementType();
  3950. Type *BTy = BPtr->getType()->getPointerElementType();
  3951. unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
  3952. // Negative distances are not plausible dependencies.
  3953. const APInt &Val = C->getValue()->getValue();
  3954. if (Val.isNegative()) {
  3955. bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
  3956. if (IsTrueDataDependence &&
  3957. (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
  3958. ATy != BTy))
  3959. return true;
  3960. DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
  3961. return false;
  3962. }
  3963. // Write to the same location with the same size.
  3964. // Could be improved to assert type sizes are the same (i32 == float, etc).
  3965. if (Val == 0) {
  3966. if (ATy == BTy)
  3967. return false;
  3968. DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
  3969. return true;
  3970. }
  3971. assert(Val.isStrictlyPositive() && "Expect a positive value");
  3972. // Positive distance bigger than max vectorization factor.
  3973. if (ATy != BTy) {
  3974. DEBUG(dbgs() <<
  3975. "LV: ReadWrite-Write positive dependency with different types\n");
  3976. return false;
  3977. }
  3978. unsigned Distance = (unsigned) Val.getZExtValue();
  3979. // Bail out early if passed-in parameters make vectorization not feasible.
  3980. unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
  3981. unsigned ForcedUnroll = VectorizationInterleave ? VectorizationInterleave : 1;
  3982. // The distance must be bigger than the size needed for a vectorized version
  3983. // of the operation and the size of the vectorized operation must not be
  3984. // bigger than the currrent maximum size.
  3985. if (Distance < 2*TypeByteSize ||
  3986. 2*TypeByteSize > MaxSafeDepDistBytes ||
  3987. Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
  3988. DEBUG(dbgs() << "LV: Failure because of Positive distance "
  3989. << Val.getSExtValue() << '\n');
  3990. return true;
  3991. }
  3992. MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
  3993. Distance : MaxSafeDepDistBytes;
  3994. bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
  3995. if (IsTrueDataDependence &&
  3996. couldPreventStoreLoadForward(Distance, TypeByteSize))
  3997. return true;
  3998. DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
  3999. " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
  4000. return false;
  4001. }
  4002. bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
  4003. MemAccessInfoSet &CheckDeps,
  4004. ValueToValueMap &Strides) {
  4005. MaxSafeDepDistBytes = -1U;
  4006. while (!CheckDeps.empty()) {
  4007. MemAccessInfo CurAccess = *CheckDeps.begin();
  4008. // Get the relevant memory access set.
  4009. EquivalenceClasses<MemAccessInfo>::iterator I =
  4010. AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
  4011. // Check accesses within this set.
  4012. EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
  4013. AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
  4014. // Check every access pair.
  4015. while (AI != AE) {
  4016. CheckDeps.erase(*AI);
  4017. EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
  4018. while (OI != AE) {
  4019. // Check every accessing instruction pair in program order.
  4020. for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
  4021. I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
  4022. for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
  4023. I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
  4024. if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
  4025. return false;
  4026. if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
  4027. return false;
  4028. }
  4029. ++OI;
  4030. }
  4031. AI++;
  4032. }
  4033. }
  4034. return true;
  4035. }
  4036. bool LoopVectorizationLegality::canVectorizeMemory() {
  4037. typedef SmallVector<Value*, 16> ValueVector;
  4038. typedef SmallPtrSet<Value*, 16> ValueSet;
  4039. // Holds the Load and Store *instructions*.
  4040. ValueVector Loads;
  4041. ValueVector Stores;
  4042. // Holds all the different accesses in the loop.
  4043. unsigned NumReads = 0;
  4044. unsigned NumReadWrites = 0;
  4045. PtrRtCheck.Pointers.clear();
  4046. PtrRtCheck.Need = false;
  4047. const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
  4048. MemoryDepChecker DepChecker(SE, DL, TheLoop);
  4049. // For each block.
  4050. for (Loop::block_iterator bb = TheLoop->block_begin(),
  4051. be = TheLoop->block_end(); bb != be; ++bb) {
  4052. // Scan the BB and collect legal loads and stores.
  4053. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  4054. ++it) {
  4055. // If this is a load, save it. If this instruction can read from memory
  4056. // but is not a load, then we quit. Notice that we don't handle function
  4057. // calls that read or write.
  4058. if (it->mayReadFromMemory()) {
  4059. // Many math library functions read the rounding mode. We will only
  4060. // vectorize a loop if it contains known function calls that don't set
  4061. // the flag. Therefore, it is safe to ignore this read from memory.
  4062. CallInst *Call = dyn_cast<CallInst>(it);
  4063. if (Call && getIntrinsicIDForCall(Call, TLI))
  4064. continue;
  4065. LoadInst *Ld = dyn_cast<LoadInst>(it);
  4066. if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
  4067. emitAnalysis(Report(Ld)
  4068. << "read with atomic ordering or volatile read");
  4069. DEBUG(dbgs() << "LV: Found a non-simple load.\n");
  4070. return false;
  4071. }
  4072. NumLoads++;
  4073. Loads.push_back(Ld);
  4074. DepChecker.addAccess(Ld);
  4075. continue;
  4076. }
  4077. // Save 'store' instructions. Abort if other instructions write to memory.
  4078. if (it->mayWriteToMemory()) {
  4079. StoreInst *St = dyn_cast<StoreInst>(it);
  4080. if (!St) {
  4081. emitAnalysis(Report(it) << "instruction cannot be vectorized");
  4082. return false;
  4083. }
  4084. if (!St->isSimple() && !IsAnnotatedParallel) {
  4085. emitAnalysis(Report(St)
  4086. << "write with atomic ordering or volatile write");
  4087. DEBUG(dbgs() << "LV: Found a non-simple store.\n");
  4088. return false;
  4089. }
  4090. NumStores++;
  4091. Stores.push_back(St);
  4092. DepChecker.addAccess(St);
  4093. }
  4094. } // Next instr.
  4095. } // Next block.
  4096. // Now we have two lists that hold the loads and the stores.
  4097. // Next, we find the pointers that they use.
  4098. // Check if we see any stores. If there are no stores, then we don't
  4099. // care if the pointers are *restrict*.
  4100. if (!Stores.size()) {
  4101. DEBUG(dbgs() << "LV: Found a read-only loop!\n");
  4102. return true;
  4103. }
  4104. AccessAnalysis::DepCandidates DependentAccesses;
  4105. AccessAnalysis Accesses(DL, AA, DependentAccesses);
  4106. // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
  4107. // multiple times on the same object. If the ptr is accessed twice, once
  4108. // for read and once for write, it will only appear once (on the write
  4109. // list). This is okay, since we are going to check for conflicts between
  4110. // writes and between reads and writes, but not between reads and reads.
  4111. ValueSet Seen;
  4112. ValueVector::iterator I, IE;
  4113. for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
  4114. StoreInst *ST = cast<StoreInst>(*I);
  4115. Value* Ptr = ST->getPointerOperand();
  4116. if (isUniform(Ptr)) {
  4117. emitAnalysis(
  4118. Report(ST)
  4119. << "write to a loop invariant address could not be vectorized");
  4120. DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
  4121. return false;
  4122. }
  4123. // If we did *not* see this pointer before, insert it to the read-write
  4124. // list. At this phase it is only a 'write' list.
  4125. if (Seen.insert(Ptr).second) {
  4126. ++NumReadWrites;
  4127. AliasAnalysis::Location Loc = AA->getLocation(ST);
  4128. // The TBAA metadata could have a control dependency on the predication
  4129. // condition, so we cannot rely on it when determining whether or not we
  4130. // need runtime pointer checks.
  4131. if (blockNeedsPredication(ST->getParent()))
  4132. Loc.AATags.TBAA = nullptr;
  4133. Accesses.addStore(Loc);
  4134. }
  4135. }
  4136. if (IsAnnotatedParallel) {
  4137. DEBUG(dbgs()
  4138. << "LV: A loop annotated parallel, ignore memory dependency "
  4139. << "checks.\n");
  4140. return true;
  4141. }
  4142. for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
  4143. LoadInst *LD = cast<LoadInst>(*I);
  4144. Value* Ptr = LD->getPointerOperand();
  4145. // If we did *not* see this pointer before, insert it to the
  4146. // read list. If we *did* see it before, then it is already in
  4147. // the read-write list. This allows us to vectorize expressions
  4148. // such as A[i] += x; Because the address of A[i] is a read-write
  4149. // pointer. This only works if the index of A[i] is consecutive.
  4150. // If the address of i is unknown (for example A[B[i]]) then we may
  4151. // read a few words, modify, and write a few words, and some of the
  4152. // words may be written to the same address.
  4153. bool IsReadOnlyPtr = false;
  4154. if (Seen.insert(Ptr).second ||
  4155. !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
  4156. ++NumReads;
  4157. IsReadOnlyPtr = true;
  4158. }
  4159. AliasAnalysis::Location Loc = AA->getLocation(LD);
  4160. // The TBAA metadata could have a control dependency on the predication
  4161. // condition, so we cannot rely on it when determining whether or not we
  4162. // need runtime pointer checks.
  4163. if (blockNeedsPredication(LD->getParent()))
  4164. Loc.AATags.TBAA = nullptr;
  4165. Accesses.addLoad(Loc, IsReadOnlyPtr);
  4166. }
  4167. // If we write (or read-write) to a single destination and there are no
  4168. // other reads in this loop then is it safe to vectorize.
  4169. if (NumReadWrites == 1 && NumReads == 0) {
  4170. DEBUG(dbgs() << "LV: Found a write-only loop!\n");
  4171. return true;
  4172. }
  4173. // Build dependence sets and check whether we need a runtime pointer bounds
  4174. // check.
  4175. Accesses.buildDependenceSets();
  4176. bool NeedRTCheck = Accesses.isRTCheckNeeded();
  4177. // Find pointers with computable bounds. We are going to use this information
  4178. // to place a runtime bound check.
  4179. unsigned NumComparisons = 0;
  4180. bool CanDoRT = false;
  4181. if (NeedRTCheck)
  4182. CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
  4183. Strides);
  4184. DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
  4185. " pointer comparisons.\n");
  4186. // If we only have one set of dependences to check pointers among we don't
  4187. // need a runtime check.
  4188. if (NumComparisons == 0 && NeedRTCheck)
  4189. NeedRTCheck = false;
  4190. // Check that we did not collect too many pointers or found an unsizeable
  4191. // pointer.
  4192. if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
  4193. PtrRtCheck.reset();
  4194. CanDoRT = false;
  4195. }
  4196. if (CanDoRT) {
  4197. DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
  4198. }
  4199. if (NeedRTCheck && !CanDoRT) {
  4200. emitAnalysis(Report() << "cannot identify array bounds");
  4201. DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
  4202. "the array bounds.\n");
  4203. PtrRtCheck.reset();
  4204. return false;
  4205. }
  4206. PtrRtCheck.Need = NeedRTCheck;
  4207. bool CanVecMem = true;
  4208. if (Accesses.isDependencyCheckNeeded()) {
  4209. DEBUG(dbgs() << "LV: Checking memory dependencies\n");
  4210. CanVecMem = DepChecker.areDepsSafe(
  4211. DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
  4212. MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
  4213. if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
  4214. DEBUG(dbgs() << "LV: Retrying with memory checks\n");
  4215. NeedRTCheck = true;
  4216. // Clear the dependency checks. We assume they are not needed.
  4217. Accesses.resetDepChecks();
  4218. PtrRtCheck.reset();
  4219. PtrRtCheck.Need = true;
  4220. CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
  4221. TheLoop, Strides, true);
  4222. // Check that we did not collect too many pointers or found an unsizeable
  4223. // pointer.
  4224. if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
  4225. if (!CanDoRT && NumComparisons > 0)
  4226. emitAnalysis(Report()
  4227. << "cannot check memory dependencies at runtime");
  4228. else
  4229. emitAnalysis(Report()
  4230. << NumComparisons << " exceeds limit of "
  4231. << RuntimeMemoryCheckThreshold
  4232. << " dependent memory operations checked at runtime");
  4233. DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
  4234. PtrRtCheck.reset();
  4235. return false;
  4236. }
  4237. CanVecMem = true;
  4238. }
  4239. }
  4240. if (!CanVecMem)
  4241. emitAnalysis(Report() << "unsafe dependent memory operations in loop");
  4242. DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
  4243. " need a runtime memory check.\n");
  4244. return CanVecMem;
  4245. }
  4246. static bool hasMultipleUsesOf(Instruction *I,
  4247. SmallPtrSetImpl<Instruction *> &Insts) {
  4248. unsigned NumUses = 0;
  4249. for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
  4250. if (Insts.count(dyn_cast<Instruction>(*Use)))
  4251. ++NumUses;
  4252. if (NumUses > 1)
  4253. return true;
  4254. }
  4255. return false;
  4256. }
  4257. static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) {
  4258. for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
  4259. if (!Set.count(dyn_cast<Instruction>(*Use)))
  4260. return false;
  4261. return true;
  4262. }
  4263. bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
  4264. ReductionKind Kind) {
  4265. if (Phi->getNumIncomingValues() != 2)
  4266. return false;
  4267. // Reduction variables are only found in the loop header block.
  4268. if (Phi->getParent() != TheLoop->getHeader())
  4269. return false;
  4270. // Obtain the reduction start value from the value that comes from the loop
  4271. // preheader.
  4272. Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
  4273. // ExitInstruction is the single value which is used outside the loop.
  4274. // We only allow for a single reduction value to be used outside the loop.
  4275. // This includes users of the reduction, variables (which form a cycle
  4276. // which ends in the phi node).
  4277. Instruction *ExitInstruction = nullptr;
  4278. // Indicates that we found a reduction operation in our scan.
  4279. bool FoundReduxOp = false;
  4280. // We start with the PHI node and scan for all of the users of this
  4281. // instruction. All users must be instructions that can be used as reduction
  4282. // variables (such as ADD). We must have a single out-of-block user. The cycle
  4283. // must include the original PHI.
  4284. bool FoundStartPHI = false;
  4285. // To recognize min/max patterns formed by a icmp select sequence, we store
  4286. // the number of instruction we saw from the recognized min/max pattern,
  4287. // to make sure we only see exactly the two instructions.
  4288. unsigned NumCmpSelectPatternInst = 0;
  4289. ReductionInstDesc ReduxDesc(false, nullptr);
  4290. SmallPtrSet<Instruction *, 8> VisitedInsts;
  4291. SmallVector<Instruction *, 8> Worklist;
  4292. Worklist.push_back(Phi);
  4293. VisitedInsts.insert(Phi);
  4294. // A value in the reduction can be used:
  4295. // - By the reduction:
  4296. // - Reduction operation:
  4297. // - One use of reduction value (safe).
  4298. // - Multiple use of reduction value (not safe).
  4299. // - PHI:
  4300. // - All uses of the PHI must be the reduction (safe).
  4301. // - Otherwise, not safe.
  4302. // - By one instruction outside of the loop (safe).
  4303. // - By further instructions outside of the loop (not safe).
  4304. // - By an instruction that is not part of the reduction (not safe).
  4305. // This is either:
  4306. // * An instruction type other than PHI or the reduction operation.
  4307. // * A PHI in the header other than the initial PHI.
  4308. while (!Worklist.empty()) {
  4309. Instruction *Cur = Worklist.back();
  4310. Worklist.pop_back();
  4311. // No Users.
  4312. // If the instruction has no users then this is a broken chain and can't be
  4313. // a reduction variable.
  4314. if (Cur->use_empty())
  4315. return false;
  4316. bool IsAPhi = isa<PHINode>(Cur);
  4317. // A header PHI use other than the original PHI.
  4318. if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
  4319. return false;
  4320. // Reductions of instructions such as Div, and Sub is only possible if the
  4321. // LHS is the reduction variable.
  4322. if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
  4323. !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
  4324. !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
  4325. return false;
  4326. // Any reduction instruction must be of one of the allowed kinds.
  4327. ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
  4328. if (!ReduxDesc.IsReduction)
  4329. return false;
  4330. // A reduction operation must only have one use of the reduction value.
  4331. if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
  4332. hasMultipleUsesOf(Cur, VisitedInsts))
  4333. return false;
  4334. // All inputs to a PHI node must be a reduction value.
  4335. if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
  4336. return false;
  4337. if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
  4338. isa<SelectInst>(Cur)))
  4339. ++NumCmpSelectPatternInst;
  4340. if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
  4341. isa<SelectInst>(Cur)))
  4342. ++NumCmpSelectPatternInst;
  4343. // Check whether we found a reduction operator.
  4344. FoundReduxOp |= !IsAPhi;
  4345. // Process users of current instruction. Push non-PHI nodes after PHI nodes
  4346. // onto the stack. This way we are going to have seen all inputs to PHI
  4347. // nodes once we get to them.
  4348. SmallVector<Instruction *, 8> NonPHIs;
  4349. SmallVector<Instruction *, 8> PHIs;
  4350. for (User *U : Cur->users()) {
  4351. Instruction *UI = cast<Instruction>(U);
  4352. // Check if we found the exit user.
  4353. BasicBlock *Parent = UI->getParent();
  4354. if (!TheLoop->contains(Parent)) {
  4355. // Exit if you find multiple outside users or if the header phi node is
  4356. // being used. In this case the user uses the value of the previous
  4357. // iteration, in which case we would loose "VF-1" iterations of the
  4358. // reduction operation if we vectorize.
  4359. if (ExitInstruction != nullptr || Cur == Phi)
  4360. return false;
  4361. // The instruction used by an outside user must be the last instruction
  4362. // before we feed back to the reduction phi. Otherwise, we loose VF-1
  4363. // operations on the value.
  4364. if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
  4365. return false;
  4366. ExitInstruction = Cur;
  4367. continue;
  4368. }
  4369. // Process instructions only once (termination). Each reduction cycle
  4370. // value must only be used once, except by phi nodes and min/max
  4371. // reductions which are represented as a cmp followed by a select.
  4372. ReductionInstDesc IgnoredVal(false, nullptr);
  4373. if (VisitedInsts.insert(UI).second) {
  4374. if (isa<PHINode>(UI))
  4375. PHIs.push_back(UI);
  4376. else
  4377. NonPHIs.push_back(UI);
  4378. } else if (!isa<PHINode>(UI) &&
  4379. ((!isa<FCmpInst>(UI) &&
  4380. !isa<ICmpInst>(UI) &&
  4381. !isa<SelectInst>(UI)) ||
  4382. !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
  4383. return false;
  4384. // Remember that we completed the cycle.
  4385. if (UI == Phi)
  4386. FoundStartPHI = true;
  4387. }
  4388. Worklist.append(PHIs.begin(), PHIs.end());
  4389. Worklist.append(NonPHIs.begin(), NonPHIs.end());
  4390. }
  4391. // This means we have seen one but not the other instruction of the
  4392. // pattern or more than just a select and cmp.
  4393. if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
  4394. NumCmpSelectPatternInst != 2)
  4395. return false;
  4396. if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
  4397. return false;
  4398. // We found a reduction var if we have reached the original phi node and we
  4399. // only have a single instruction with out-of-loop users.
  4400. // This instruction is allowed to have out-of-loop users.
  4401. AllowedExit.insert(ExitInstruction);
  4402. // Save the description of this reduction variable.
  4403. ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
  4404. ReduxDesc.MinMaxKind);
  4405. Reductions[Phi] = RD;
  4406. // We've ended the cycle. This is a reduction variable if we have an
  4407. // outside user and it has a binary op.
  4408. return true;
  4409. }
  4410. /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
  4411. /// pattern corresponding to a min(X, Y) or max(X, Y).
  4412. LoopVectorizationLegality::ReductionInstDesc
  4413. LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
  4414. ReductionInstDesc &Prev) {
  4415. assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
  4416. "Expect a select instruction");
  4417. Instruction *Cmp = nullptr;
  4418. SelectInst *Select = nullptr;
  4419. // We must handle the select(cmp()) as a single instruction. Advance to the
  4420. // select.
  4421. if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
  4422. if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
  4423. return ReductionInstDesc(false, I);
  4424. return ReductionInstDesc(Select, Prev.MinMaxKind);
  4425. }
  4426. // Only handle single use cases for now.
  4427. if (!(Select = dyn_cast<SelectInst>(I)))
  4428. return ReductionInstDesc(false, I);
  4429. if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
  4430. !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
  4431. return ReductionInstDesc(false, I);
  4432. if (!Cmp->hasOneUse())
  4433. return ReductionInstDesc(false, I);
  4434. Value *CmpLeft;
  4435. Value *CmpRight;
  4436. // Look for a min/max pattern.
  4437. if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  4438. return ReductionInstDesc(Select, MRK_UIntMin);
  4439. else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  4440. return ReductionInstDesc(Select, MRK_UIntMax);
  4441. else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  4442. return ReductionInstDesc(Select, MRK_SIntMax);
  4443. else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  4444. return ReductionInstDesc(Select, MRK_SIntMin);
  4445. else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  4446. return ReductionInstDesc(Select, MRK_FloatMin);
  4447. else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  4448. return ReductionInstDesc(Select, MRK_FloatMax);
  4449. else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  4450. return ReductionInstDesc(Select, MRK_FloatMin);
  4451. else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  4452. return ReductionInstDesc(Select, MRK_FloatMax);
  4453. return ReductionInstDesc(false, I);
  4454. }
  4455. LoopVectorizationLegality::ReductionInstDesc
  4456. LoopVectorizationLegality::isReductionInstr(Instruction *I,
  4457. ReductionKind Kind,
  4458. ReductionInstDesc &Prev) {
  4459. bool FP = I->getType()->isFloatingPointTy();
  4460. bool FastMath = FP && I->hasUnsafeAlgebra();
  4461. switch (I->getOpcode()) {
  4462. default:
  4463. return ReductionInstDesc(false, I);
  4464. case Instruction::PHI:
  4465. if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
  4466. Kind != RK_FloatMinMax))
  4467. return ReductionInstDesc(false, I);
  4468. return ReductionInstDesc(I, Prev.MinMaxKind);
  4469. case Instruction::Sub:
  4470. case Instruction::Add:
  4471. return ReductionInstDesc(Kind == RK_IntegerAdd, I);
  4472. case Instruction::Mul:
  4473. return ReductionInstDesc(Kind == RK_IntegerMult, I);
  4474. case Instruction::And:
  4475. return ReductionInstDesc(Kind == RK_IntegerAnd, I);
  4476. case Instruction::Or:
  4477. return ReductionInstDesc(Kind == RK_IntegerOr, I);
  4478. case Instruction::Xor:
  4479. return ReductionInstDesc(Kind == RK_IntegerXor, I);
  4480. case Instruction::FMul:
  4481. return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
  4482. case Instruction::FSub:
  4483. case Instruction::FAdd:
  4484. return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
  4485. case Instruction::FCmp:
  4486. case Instruction::ICmp:
  4487. case Instruction::Select:
  4488. if (Kind != RK_IntegerMinMax &&
  4489. (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
  4490. return ReductionInstDesc(false, I);
  4491. return isMinMaxSelectCmpPattern(I, Prev);
  4492. }
  4493. }
  4494. LoopVectorizationLegality::InductionKind
  4495. LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
  4496. Type *PhiTy = Phi->getType();
  4497. // We only handle integer and pointer inductions variables.
  4498. if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
  4499. return IK_NoInduction;
  4500. // Check that the PHI is consecutive.
  4501. const SCEV *PhiScev = SE->getSCEV(Phi);
  4502. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
  4503. if (!AR) {
  4504. DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
  4505. return IK_NoInduction;
  4506. }
  4507. const SCEV *Step = AR->getStepRecurrence(*SE);
  4508. // Integer inductions need to have a stride of one.
  4509. if (PhiTy->isIntegerTy()) {
  4510. if (Step->isOne())
  4511. return IK_IntInduction;
  4512. if (Step->isAllOnesValue())
  4513. return IK_ReverseIntInduction;
  4514. return IK_NoInduction;
  4515. }
  4516. // Calculate the pointer stride and check if it is consecutive.
  4517. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  4518. if (!C)
  4519. return IK_NoInduction;
  4520. assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
  4521. Type *PointerElementType = PhiTy->getPointerElementType();
  4522. // The pointer stride cannot be determined if the pointer element type is not
  4523. // sized.
  4524. if (!PointerElementType->isSized())
  4525. return IK_NoInduction;
  4526. uint64_t Size = DL->getTypeAllocSize(PointerElementType);
  4527. if (C->getValue()->equalsInt(Size))
  4528. return IK_PtrInduction;
  4529. else if (C->getValue()->equalsInt(0 - Size))
  4530. return IK_ReversePtrInduction;
  4531. return IK_NoInduction;
  4532. }
  4533. bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
  4534. Value *In0 = const_cast<Value*>(V);
  4535. PHINode *PN = dyn_cast_or_null<PHINode>(In0);
  4536. if (!PN)
  4537. return false;
  4538. return Inductions.count(PN);
  4539. }
  4540. bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
  4541. assert(TheLoop->contains(BB) && "Unknown block used");
  4542. // Blocks that do not dominate the latch need predication.
  4543. BasicBlock* Latch = TheLoop->getLoopLatch();
  4544. return !DT->dominates(BB, Latch);
  4545. }
  4546. bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
  4547. SmallPtrSetImpl<Value *> &SafePtrs) {
  4548. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  4549. // We might be able to hoist the load.
  4550. if (it->mayReadFromMemory()) {
  4551. LoadInst *LI = dyn_cast<LoadInst>(it);
  4552. if (!LI || !SafePtrs.count(LI->getPointerOperand()))
  4553. return false;
  4554. }
  4555. // We don't predicate stores at the moment.
  4556. if (it->mayWriteToMemory()) {
  4557. StoreInst *SI = dyn_cast<StoreInst>(it);
  4558. // We only support predication of stores in basic blocks with one
  4559. // predecessor.
  4560. if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
  4561. !SafePtrs.count(SI->getPointerOperand()) ||
  4562. !SI->getParent()->getSinglePredecessor())
  4563. return false;
  4564. }
  4565. if (it->mayThrow())
  4566. return false;
  4567. // Check that we don't have a constant expression that can trap as operand.
  4568. for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
  4569. OI != OE; ++OI) {
  4570. if (Constant *C = dyn_cast<Constant>(*OI))
  4571. if (C->canTrap())
  4572. return false;
  4573. }
  4574. // The instructions below can trap.
  4575. switch (it->getOpcode()) {
  4576. default: continue;
  4577. case Instruction::UDiv:
  4578. case Instruction::SDiv:
  4579. case Instruction::URem:
  4580. case Instruction::SRem:
  4581. return false;
  4582. }
  4583. }
  4584. return true;
  4585. }
  4586. LoopVectorizationCostModel::VectorizationFactor
  4587. LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
  4588. // Width 1 means no vectorize
  4589. VectorizationFactor Factor = { 1U, 0U };
  4590. if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
  4591. emitAnalysis(Report() << "runtime pointer checks needed. Enable vectorization of this loop with '#pragma clang loop vectorize(enable)' when compiling with -Os");
  4592. DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
  4593. return Factor;
  4594. }
  4595. if (!EnableCondStoresVectorization && Legal->NumPredStores) {
  4596. emitAnalysis(Report() << "store that is conditionally executed prevents vectorization");
  4597. DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
  4598. return Factor;
  4599. }
  4600. // Find the trip count.
  4601. unsigned TC = SE->getSmallConstantTripCount(TheLoop);
  4602. DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
  4603. unsigned WidestType = getWidestType();
  4604. unsigned WidestRegister = TTI.getRegisterBitWidth(true);
  4605. unsigned MaxSafeDepDist = -1U;
  4606. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4607. MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
  4608. WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
  4609. WidestRegister : MaxSafeDepDist);
  4610. unsigned MaxVectorSize = WidestRegister / WidestType;
  4611. DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
  4612. DEBUG(dbgs() << "LV: The Widest register is: "
  4613. << WidestRegister << " bits.\n");
  4614. if (MaxVectorSize == 0) {
  4615. DEBUG(dbgs() << "LV: The target has no vector registers.\n");
  4616. MaxVectorSize = 1;
  4617. }
  4618. assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
  4619. " into one vector!");
  4620. unsigned VF = MaxVectorSize;
  4621. // If we optimize the program for size, avoid creating the tail loop.
  4622. if (OptForSize) {
  4623. // If we are unable to calculate the trip count then don't try to vectorize.
  4624. if (TC < 2) {
  4625. emitAnalysis(Report() << "unable to calculate the loop count due to complex control flow");
  4626. DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
  4627. return Factor;
  4628. }
  4629. // Find the maximum SIMD width that can fit within the trip count.
  4630. VF = TC % MaxVectorSize;
  4631. if (VF == 0)
  4632. VF = MaxVectorSize;
  4633. // If the trip count that we found modulo the vectorization factor is not
  4634. // zero then we require a tail.
  4635. if (VF < 2) {
  4636. emitAnalysis(Report() << "cannot optimize for size and vectorize at the "
  4637. "same time. Enable vectorization of this loop "
  4638. "with '#pragma clang loop vectorize(enable)' "
  4639. "when compiling with -Os");
  4640. DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
  4641. return Factor;
  4642. }
  4643. }
  4644. int UserVF = Hints->getWidth();
  4645. if (UserVF != 0) {
  4646. assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
  4647. DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
  4648. Factor.Width = UserVF;
  4649. return Factor;
  4650. }
  4651. float Cost = expectedCost(1);
  4652. #ifndef NDEBUG
  4653. const float ScalarCost = Cost;
  4654. #endif /* NDEBUG */
  4655. unsigned Width = 1;
  4656. DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
  4657. bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
  4658. // Ignore scalar width, because the user explicitly wants vectorization.
  4659. if (ForceVectorization && VF > 1) {
  4660. Width = 2;
  4661. Cost = expectedCost(Width) / (float)Width;
  4662. }
  4663. for (unsigned i=2; i <= VF; i*=2) {
  4664. // Notice that the vector loop needs to be executed less times, so
  4665. // we need to divide the cost of the vector loops by the width of
  4666. // the vector elements.
  4667. float VectorCost = expectedCost(i) / (float)i;
  4668. DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
  4669. (int)VectorCost << ".\n");
  4670. if (VectorCost < Cost) {
  4671. Cost = VectorCost;
  4672. Width = i;
  4673. }
  4674. }
  4675. DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
  4676. << "LV: Vectorization seems to be not beneficial, "
  4677. << "but was forced by a user.\n");
  4678. DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
  4679. Factor.Width = Width;
  4680. Factor.Cost = Width * Cost;
  4681. return Factor;
  4682. }
  4683. unsigned LoopVectorizationCostModel::getWidestType() {
  4684. unsigned MaxWidth = 8;
  4685. // For each block.
  4686. for (Loop::block_iterator bb = TheLoop->block_begin(),
  4687. be = TheLoop->block_end(); bb != be; ++bb) {
  4688. BasicBlock *BB = *bb;
  4689. // For each instruction in the loop.
  4690. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  4691. Type *T = it->getType();
  4692. // Ignore ephemeral values.
  4693. if (EphValues.count(it))
  4694. continue;
  4695. // Only examine Loads, Stores and PHINodes.
  4696. if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
  4697. continue;
  4698. // Examine PHI nodes that are reduction variables.
  4699. if (PHINode *PN = dyn_cast<PHINode>(it))
  4700. if (!Legal->getReductionVars()->count(PN))
  4701. continue;
  4702. // Examine the stored values.
  4703. if (StoreInst *ST = dyn_cast<StoreInst>(it))
  4704. T = ST->getValueOperand()->getType();
  4705. // Ignore loaded pointer types and stored pointer types that are not
  4706. // consecutive. However, we do want to take consecutive stores/loads of
  4707. // pointer vectors into account.
  4708. if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
  4709. continue;
  4710. MaxWidth = std::max(MaxWidth,
  4711. (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
  4712. }
  4713. }
  4714. return MaxWidth;
  4715. }
  4716. unsigned
  4717. LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
  4718. unsigned VF,
  4719. unsigned LoopCost) {
  4720. // -- The unroll heuristics --
  4721. // We unroll the loop in order to expose ILP and reduce the loop overhead.
  4722. // There are many micro-architectural considerations that we can't predict
  4723. // at this level. For example, frontend pressure (on decode or fetch) due to
  4724. // code size, or the number and capabilities of the execution ports.
  4725. //
  4726. // We use the following heuristics to select the unroll factor:
  4727. // 1. If the code has reductions, then we unroll in order to break the cross
  4728. // iteration dependency.
  4729. // 2. If the loop is really small, then we unroll in order to reduce the loop
  4730. // overhead.
  4731. // 3. We don't unroll if we think that we will spill registers to memory due
  4732. // to the increased register pressure.
  4733. // Use the user preference, unless 'auto' is selected.
  4734. int UserUF = Hints->getInterleave();
  4735. if (UserUF != 0)
  4736. return UserUF;
  4737. // When we optimize for size, we don't unroll.
  4738. if (OptForSize)
  4739. return 1;
  4740. // We used the distance for the unroll factor.
  4741. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4742. return 1;
  4743. // Do not unroll loops with a relatively small trip count.
  4744. unsigned TC = SE->getSmallConstantTripCount(TheLoop);
  4745. if (TC > 1 && TC < TinyTripCountUnrollThreshold)
  4746. return 1;
  4747. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
  4748. DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
  4749. " registers\n");
  4750. if (VF == 1) {
  4751. if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
  4752. TargetNumRegisters = ForceTargetNumScalarRegs;
  4753. } else {
  4754. if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
  4755. TargetNumRegisters = ForceTargetNumVectorRegs;
  4756. }
  4757. LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
  4758. // We divide by these constants so assume that we have at least one
  4759. // instruction that uses at least one register.
  4760. R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
  4761. R.NumInstructions = std::max(R.NumInstructions, 1U);
  4762. // We calculate the unroll factor using the following formula.
  4763. // Subtract the number of loop invariants from the number of available
  4764. // registers. These registers are used by all of the unrolled instances.
  4765. // Next, divide the remaining registers by the number of registers that is
  4766. // required by the loop, in order to estimate how many parallel instances
  4767. // fit without causing spills. All of this is rounded down if necessary to be
  4768. // a power of two. We want power of two unroll factors to simplify any
  4769. // addressing operations or alignment considerations.
  4770. unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
  4771. R.MaxLocalUsers);
  4772. // Don't count the induction variable as unrolled.
  4773. if (EnableIndVarRegisterHeur)
  4774. UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
  4775. std::max(1U, (R.MaxLocalUsers - 1)));
  4776. // Clamp the unroll factor ranges to reasonable factors.
  4777. unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
  4778. // Check if the user has overridden the unroll max.
  4779. if (VF == 1) {
  4780. if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
  4781. MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
  4782. } else {
  4783. if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
  4784. MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
  4785. }
  4786. // If we did not calculate the cost for VF (because the user selected the VF)
  4787. // then we calculate the cost of VF here.
  4788. if (LoopCost == 0)
  4789. LoopCost = expectedCost(VF);
  4790. // Clamp the calculated UF to be between the 1 and the max unroll factor
  4791. // that the target allows.
  4792. if (UF > MaxInterleaveSize)
  4793. UF = MaxInterleaveSize;
  4794. else if (UF < 1)
  4795. UF = 1;
  4796. // Unroll if we vectorized this loop and there is a reduction that could
  4797. // benefit from unrolling.
  4798. if (VF > 1 && Legal->getReductionVars()->size()) {
  4799. DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
  4800. return UF;
  4801. }
  4802. // Note that if we've already vectorized the loop we will have done the
  4803. // runtime check and so unrolling won't require further checks.
  4804. bool UnrollingRequiresRuntimePointerCheck =
  4805. (VF == 1 && Legal->getRuntimePointerCheck()->Need);
  4806. // We want to unroll small loops in order to reduce the loop overhead and
  4807. // potentially expose ILP opportunities.
  4808. DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
  4809. if (!UnrollingRequiresRuntimePointerCheck &&
  4810. LoopCost < SmallLoopCost) {
  4811. // We assume that the cost overhead is 1 and we use the cost model
  4812. // to estimate the cost of the loop and unroll until the cost of the
  4813. // loop overhead is about 5% of the cost of the loop.
  4814. unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
  4815. // Unroll until store/load ports (estimated by max unroll factor) are
  4816. // saturated.
  4817. unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
  4818. unsigned LoadsUF = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
  4819. // If we have a scalar reduction (vector reductions are already dealt with
  4820. // by this point), we can increase the critical path length if the loop
  4821. // we're unrolling is inside another loop. Limit, by default to 2, so the
  4822. // critical path only gets increased by one reduction operation.
  4823. if (Legal->getReductionVars()->size() &&
  4824. TheLoop->getLoopDepth() > 1) {
  4825. unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
  4826. SmallUF = std::min(SmallUF, F);
  4827. StoresUF = std::min(StoresUF, F);
  4828. LoadsUF = std::min(LoadsUF, F);
  4829. }
  4830. if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
  4831. DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
  4832. return std::max(StoresUF, LoadsUF);
  4833. }
  4834. DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
  4835. return SmallUF;
  4836. }
  4837. DEBUG(dbgs() << "LV: Not Unrolling.\n");
  4838. return 1;
  4839. }
  4840. LoopVectorizationCostModel::RegisterUsage
  4841. LoopVectorizationCostModel::calculateRegisterUsage() {
  4842. // This function calculates the register usage by measuring the highest number
  4843. // of values that are alive at a single location. Obviously, this is a very
  4844. // rough estimation. We scan the loop in a topological order in order and
  4845. // assign a number to each instruction. We use RPO to ensure that defs are
  4846. // met before their users. We assume that each instruction that has in-loop
  4847. // users starts an interval. We record every time that an in-loop value is
  4848. // used, so we have a list of the first and last occurrences of each
  4849. // instruction. Next, we transpose this data structure into a multi map that
  4850. // holds the list of intervals that *end* at a specific location. This multi
  4851. // map allows us to perform a linear search. We scan the instructions linearly
  4852. // and record each time that a new interval starts, by placing it in a set.
  4853. // If we find this value in the multi-map then we remove it from the set.
  4854. // The max register usage is the maximum size of the set.
  4855. // We also search for instructions that are defined outside the loop, but are
  4856. // used inside the loop. We need this number separately from the max-interval
  4857. // usage number because when we unroll, loop-invariant values do not take
  4858. // more register.
  4859. LoopBlocksDFS DFS(TheLoop);
  4860. DFS.perform(LI);
  4861. RegisterUsage R;
  4862. R.NumInstructions = 0;
  4863. // Each 'key' in the map opens a new interval. The values
  4864. // of the map are the index of the 'last seen' usage of the
  4865. // instruction that is the key.
  4866. typedef DenseMap<Instruction*, unsigned> IntervalMap;
  4867. // Maps instruction to its index.
  4868. DenseMap<unsigned, Instruction*> IdxToInstr;
  4869. // Marks the end of each interval.
  4870. IntervalMap EndPoint;
  4871. // Saves the list of instruction indices that are used in the loop.
  4872. SmallSet<Instruction*, 8> Ends;
  4873. // Saves the list of values that are used in the loop but are
  4874. // defined outside the loop, such as arguments and constants.
  4875. SmallPtrSet<Value*, 8> LoopInvariants;
  4876. unsigned Index = 0;
  4877. for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
  4878. be = DFS.endRPO(); bb != be; ++bb) {
  4879. R.NumInstructions += (*bb)->size();
  4880. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  4881. ++it) {
  4882. Instruction *I = it;
  4883. IdxToInstr[Index++] = I;
  4884. // Save the end location of each USE.
  4885. for (unsigned i = 0; i < I->getNumOperands(); ++i) {
  4886. Value *U = I->getOperand(i);
  4887. Instruction *Instr = dyn_cast<Instruction>(U);
  4888. // Ignore non-instruction values such as arguments, constants, etc.
  4889. if (!Instr) continue;
  4890. // If this instruction is outside the loop then record it and continue.
  4891. if (!TheLoop->contains(Instr)) {
  4892. LoopInvariants.insert(Instr);
  4893. continue;
  4894. }
  4895. // Overwrite previous end points.
  4896. EndPoint[Instr] = Index;
  4897. Ends.insert(Instr);
  4898. }
  4899. }
  4900. }
  4901. // Saves the list of intervals that end with the index in 'key'.
  4902. typedef SmallVector<Instruction*, 2> InstrList;
  4903. DenseMap<unsigned, InstrList> TransposeEnds;
  4904. // Transpose the EndPoints to a list of values that end at each index.
  4905. for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
  4906. it != e; ++it)
  4907. TransposeEnds[it->second].push_back(it->first);
  4908. SmallSet<Instruction*, 8> OpenIntervals;
  4909. unsigned MaxUsage = 0;
  4910. DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
  4911. for (unsigned int i = 0; i < Index; ++i) {
  4912. Instruction *I = IdxToInstr[i];
  4913. // Ignore instructions that are never used within the loop.
  4914. if (!Ends.count(I)) continue;
  4915. // Ignore ephemeral values.
  4916. if (EphValues.count(I))
  4917. continue;
  4918. // Remove all of the instructions that end at this location.
  4919. InstrList &List = TransposeEnds[i];
  4920. for (unsigned int j=0, e = List.size(); j < e; ++j)
  4921. OpenIntervals.erase(List[j]);
  4922. // Count the number of live interals.
  4923. MaxUsage = std::max(MaxUsage, OpenIntervals.size());
  4924. DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
  4925. OpenIntervals.size() << '\n');
  4926. // Add the current instruction to the list of open intervals.
  4927. OpenIntervals.insert(I);
  4928. }
  4929. unsigned Invariant = LoopInvariants.size();
  4930. DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
  4931. DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
  4932. DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
  4933. R.LoopInvariantRegs = Invariant;
  4934. R.MaxLocalUsers = MaxUsage;
  4935. return R;
  4936. }
  4937. unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
  4938. unsigned Cost = 0;
  4939. // For each block.
  4940. for (Loop::block_iterator bb = TheLoop->block_begin(),
  4941. be = TheLoop->block_end(); bb != be; ++bb) {
  4942. unsigned BlockCost = 0;
  4943. BasicBlock *BB = *bb;
  4944. // For each instruction in the old loop.
  4945. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  4946. // Skip dbg intrinsics.
  4947. if (isa<DbgInfoIntrinsic>(it))
  4948. continue;
  4949. // Ignore ephemeral values.
  4950. if (EphValues.count(it))
  4951. continue;
  4952. unsigned C = getInstructionCost(it, VF);
  4953. // Check if we should override the cost.
  4954. if (ForceTargetInstructionCost.getNumOccurrences() > 0)
  4955. C = ForceTargetInstructionCost;
  4956. BlockCost += C;
  4957. DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
  4958. VF << " For instruction: " << *it << '\n');
  4959. }
  4960. // We assume that if-converted blocks have a 50% chance of being executed.
  4961. // When the code is scalar then some of the blocks are avoided due to CF.
  4962. // When the code is vectorized we execute all code paths.
  4963. if (VF == 1 && Legal->blockNeedsPredication(*bb))
  4964. BlockCost /= 2;
  4965. Cost += BlockCost;
  4966. }
  4967. return Cost;
  4968. }
  4969. /// \brief Check whether the address computation for a non-consecutive memory
  4970. /// access looks like an unlikely candidate for being merged into the indexing
  4971. /// mode.
  4972. ///
  4973. /// We look for a GEP which has one index that is an induction variable and all
  4974. /// other indices are loop invariant. If the stride of this access is also
  4975. /// within a small bound we decide that this address computation can likely be
  4976. /// merged into the addressing mode.
  4977. /// In all other cases, we identify the address computation as complex.
  4978. static bool isLikelyComplexAddressComputation(Value *Ptr,
  4979. LoopVectorizationLegality *Legal,
  4980. ScalarEvolution *SE,
  4981. const Loop *TheLoop) {
  4982. GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  4983. if (!Gep)
  4984. return true;
  4985. // We are looking for a gep with all loop invariant indices except for one
  4986. // which should be an induction variable.
  4987. unsigned NumOperands = Gep->getNumOperands();
  4988. for (unsigned i = 1; i < NumOperands; ++i) {
  4989. Value *Opd = Gep->getOperand(i);
  4990. if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
  4991. !Legal->isInductionVariable(Opd))
  4992. return true;
  4993. }
  4994. // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
  4995. // can likely be merged into the address computation.
  4996. unsigned MaxMergeDistance = 64;
  4997. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
  4998. if (!AddRec)
  4999. return true;
  5000. // Check the step is constant.
  5001. const SCEV *Step = AddRec->getStepRecurrence(*SE);
  5002. // Calculate the pointer stride and check if it is consecutive.
  5003. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  5004. if (!C)
  5005. return true;
  5006. const APInt &APStepVal = C->getValue()->getValue();
  5007. // Huge step value - give up.
  5008. if (APStepVal.getBitWidth() > 64)
  5009. return true;
  5010. int64_t StepVal = APStepVal.getSExtValue();
  5011. return StepVal > MaxMergeDistance;
  5012. }
  5013. static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
  5014. if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
  5015. return true;
  5016. return false;
  5017. }
  5018. unsigned
  5019. LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
  5020. // If we know that this instruction will remain uniform, check the cost of
  5021. // the scalar version.
  5022. if (Legal->isUniformAfterVectorization(I))
  5023. VF = 1;
  5024. Type *RetTy = I->getType();
  5025. Type *VectorTy = ToVectorTy(RetTy, VF);
  5026. // TODO: We need to estimate the cost of intrinsic calls.
  5027. switch (I->getOpcode()) {
  5028. case Instruction::GetElementPtr:
  5029. // We mark this instruction as zero-cost because the cost of GEPs in
  5030. // vectorized code depends on whether the corresponding memory instruction
  5031. // is scalarized or not. Therefore, we handle GEPs with the memory
  5032. // instruction cost.
  5033. return 0;
  5034. case Instruction::Br: {
  5035. return TTI.getCFInstrCost(I->getOpcode());
  5036. }
  5037. case Instruction::PHI:
  5038. //TODO: IF-converted IFs become selects.
  5039. return 0;
  5040. case Instruction::Add:
  5041. case Instruction::FAdd:
  5042. case Instruction::Sub:
  5043. case Instruction::FSub:
  5044. case Instruction::Mul:
  5045. case Instruction::FMul:
  5046. case Instruction::UDiv:
  5047. case Instruction::SDiv:
  5048. case Instruction::FDiv:
  5049. case Instruction::URem:
  5050. case Instruction::SRem:
  5051. case Instruction::FRem:
  5052. case Instruction::Shl:
  5053. case Instruction::LShr:
  5054. case Instruction::AShr:
  5055. case Instruction::And:
  5056. case Instruction::Or:
  5057. case Instruction::Xor: {
  5058. // Since we will replace the stride by 1 the multiplication should go away.
  5059. if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
  5060. return 0;
  5061. // Certain instructions can be cheaper to vectorize if they have a constant
  5062. // second vector operand. One example of this are shifts on x86.
  5063. TargetTransformInfo::OperandValueKind Op1VK =
  5064. TargetTransformInfo::OK_AnyValue;
  5065. TargetTransformInfo::OperandValueKind Op2VK =
  5066. TargetTransformInfo::OK_AnyValue;
  5067. TargetTransformInfo::OperandValueProperties Op1VP =
  5068. TargetTransformInfo::OP_None;
  5069. TargetTransformInfo::OperandValueProperties Op2VP =
  5070. TargetTransformInfo::OP_None;
  5071. Value *Op2 = I->getOperand(1);
  5072. // Check for a splat of a constant or for a non uniform vector of constants.
  5073. if (isa<ConstantInt>(Op2)) {
  5074. ConstantInt *CInt = cast<ConstantInt>(Op2);
  5075. if (CInt && CInt->getValue().isPowerOf2())
  5076. Op2VP = TargetTransformInfo::OP_PowerOf2;
  5077. Op2VK = TargetTransformInfo::OK_UniformConstantValue;
  5078. } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
  5079. Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
  5080. Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
  5081. if (SplatValue) {
  5082. ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
  5083. if (CInt && CInt->getValue().isPowerOf2())
  5084. Op2VP = TargetTransformInfo::OP_PowerOf2;
  5085. Op2VK = TargetTransformInfo::OK_UniformConstantValue;
  5086. }
  5087. }
  5088. return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
  5089. Op1VP, Op2VP);
  5090. }
  5091. case Instruction::Select: {
  5092. SelectInst *SI = cast<SelectInst>(I);
  5093. const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
  5094. bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
  5095. Type *CondTy = SI->getCondition()->getType();
  5096. if (!ScalarCond)
  5097. CondTy = VectorType::get(CondTy, VF);
  5098. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
  5099. }
  5100. case Instruction::ICmp:
  5101. case Instruction::FCmp: {
  5102. Type *ValTy = I->getOperand(0)->getType();
  5103. VectorTy = ToVectorTy(ValTy, VF);
  5104. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
  5105. }
  5106. case Instruction::Store:
  5107. case Instruction::Load: {
  5108. StoreInst *SI = dyn_cast<StoreInst>(I);
  5109. LoadInst *LI = dyn_cast<LoadInst>(I);
  5110. Type *ValTy = (SI ? SI->getValueOperand()->getType() :
  5111. LI->getType());
  5112. VectorTy = ToVectorTy(ValTy, VF);
  5113. unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
  5114. unsigned AS = SI ? SI->getPointerAddressSpace() :
  5115. LI->getPointerAddressSpace();
  5116. Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
  5117. // We add the cost of address computation here instead of with the gep
  5118. // instruction because only here we know whether the operation is
  5119. // scalarized.
  5120. if (VF == 1)
  5121. return TTI.getAddressComputationCost(VectorTy) +
  5122. TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
  5123. // Scalarized loads/stores.
  5124. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  5125. bool Reverse = ConsecutiveStride < 0;
  5126. unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
  5127. unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
  5128. if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
  5129. bool IsComplexComputation =
  5130. isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
  5131. unsigned Cost = 0;
  5132. // The cost of extracting from the value vector and pointer vector.
  5133. Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
  5134. for (unsigned i = 0; i < VF; ++i) {
  5135. // The cost of extracting the pointer operand.
  5136. Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
  5137. // In case of STORE, the cost of ExtractElement from the vector.
  5138. // In case of LOAD, the cost of InsertElement into the returned
  5139. // vector.
  5140. Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
  5141. Instruction::InsertElement,
  5142. VectorTy, i);
  5143. }
  5144. // The cost of the scalar loads/stores.
  5145. Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
  5146. Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
  5147. Alignment, AS);
  5148. return Cost;
  5149. }
  5150. // Wide load/stores.
  5151. unsigned Cost = TTI.getAddressComputationCost(VectorTy);
  5152. Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
  5153. if (Reverse)
  5154. Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
  5155. VectorTy, 0);
  5156. return Cost;
  5157. }
  5158. case Instruction::ZExt:
  5159. case Instruction::SExt:
  5160. case Instruction::FPToUI:
  5161. case Instruction::FPToSI:
  5162. case Instruction::FPExt:
  5163. case Instruction::PtrToInt:
  5164. case Instruction::IntToPtr:
  5165. case Instruction::SIToFP:
  5166. case Instruction::UIToFP:
  5167. case Instruction::Trunc:
  5168. case Instruction::FPTrunc:
  5169. case Instruction::BitCast: {
  5170. // We optimize the truncation of induction variable.
  5171. // The cost of these is the same as the scalar operation.
  5172. if (I->getOpcode() == Instruction::Trunc &&
  5173. Legal->isInductionVariable(I->getOperand(0)))
  5174. return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
  5175. I->getOperand(0)->getType());
  5176. Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
  5177. return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
  5178. }
  5179. case Instruction::Call: {
  5180. CallInst *CI = cast<CallInst>(I);
  5181. Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
  5182. assert(ID && "Not an intrinsic call!");
  5183. Type *RetTy = ToVectorTy(CI->getType(), VF);
  5184. SmallVector<Type*, 4> Tys;
  5185. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
  5186. Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
  5187. return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
  5188. }
  5189. default: {
  5190. // We are scalarizing the instruction. Return the cost of the scalar
  5191. // instruction, plus the cost of insert and extract into vector
  5192. // elements, times the vector width.
  5193. unsigned Cost = 0;
  5194. if (!RetTy->isVoidTy() && VF != 1) {
  5195. unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
  5196. VectorTy);
  5197. unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
  5198. VectorTy);
  5199. // The cost of inserting the results plus extracting each one of the
  5200. // operands.
  5201. Cost += VF * (InsCost + ExtCost * I->getNumOperands());
  5202. }
  5203. // The cost of executing VF copies of the scalar instruction. This opcode
  5204. // is unknown. Assume that it is the same as 'mul'.
  5205. Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
  5206. return Cost;
  5207. }
  5208. }// end of switch.
  5209. }
  5210. Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
  5211. if (Scalar->isVoidTy() || VF == 1)
  5212. return Scalar;
  5213. return VectorType::get(Scalar, VF);
  5214. }
  5215. char LoopVectorize::ID = 0;
  5216. static const char lv_name[] = "Loop Vectorization";
  5217. INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
  5218. INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
  5219. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  5220. INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
  5221. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
  5222. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  5223. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  5224. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  5225. INITIALIZE_PASS_DEPENDENCY(LoopInfo)
  5226. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  5227. INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
  5228. namespace llvm {
  5229. Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
  5230. return new LoopVectorize(NoUnrolling, AlwaysVectorize);
  5231. }
  5232. }
  5233. bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
  5234. // Check for a store.
  5235. if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
  5236. return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
  5237. // Check for a load.
  5238. if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  5239. return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
  5240. return false;
  5241. }
  5242. void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
  5243. bool IfPredicateStore) {
  5244. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  5245. // Holds vector parameters or scalars, in case of uniform vals.
  5246. SmallVector<VectorParts, 4> Params;
  5247. setDebugLocFromInst(Builder, Instr);
  5248. // Find all of the vectorized parameters.
  5249. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  5250. Value *SrcOp = Instr->getOperand(op);
  5251. // If we are accessing the old induction variable, use the new one.
  5252. if (SrcOp == OldInduction) {
  5253. Params.push_back(getVectorValue(SrcOp));
  5254. continue;
  5255. }
  5256. // Try using previously calculated values.
  5257. Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
  5258. // If the src is an instruction that appeared earlier in the basic block
  5259. // then it should already be vectorized.
  5260. if (SrcInst && OrigLoop->contains(SrcInst)) {
  5261. assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
  5262. // The parameter is a vector value from earlier.
  5263. Params.push_back(WidenMap.get(SrcInst));
  5264. } else {
  5265. // The parameter is a scalar from outside the loop. Maybe even a constant.
  5266. VectorParts Scalars;
  5267. Scalars.append(UF, SrcOp);
  5268. Params.push_back(Scalars);
  5269. }
  5270. }
  5271. assert(Params.size() == Instr->getNumOperands() &&
  5272. "Invalid number of operands");
  5273. // Does this instruction return a value ?
  5274. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  5275. Value *UndefVec = IsVoidRetTy ? nullptr :
  5276. UndefValue::get(Instr->getType());
  5277. // Create a new entry in the WidenMap and initialize it to Undef or Null.
  5278. VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
  5279. Instruction *InsertPt = Builder.GetInsertPoint();
  5280. BasicBlock *IfBlock = Builder.GetInsertBlock();
  5281. BasicBlock *CondBlock = nullptr;
  5282. VectorParts Cond;
  5283. Loop *VectorLp = nullptr;
  5284. if (IfPredicateStore) {
  5285. assert(Instr->getParent()->getSinglePredecessor() &&
  5286. "Only support single predecessor blocks");
  5287. Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
  5288. Instr->getParent());
  5289. VectorLp = LI->getLoopFor(IfBlock);
  5290. assert(VectorLp && "Must have a loop for this block");
  5291. }
  5292. // For each vector unroll 'part':
  5293. for (unsigned Part = 0; Part < UF; ++Part) {
  5294. // For each scalar that we create:
  5295. // Start an "if (pred) a[i] = ..." block.
  5296. Value *Cmp = nullptr;
  5297. if (IfPredicateStore) {
  5298. if (Cond[Part]->getType()->isVectorTy())
  5299. Cond[Part] =
  5300. Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
  5301. Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
  5302. ConstantInt::get(Cond[Part]->getType(), 1));
  5303. CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
  5304. LoopVectorBody.push_back(CondBlock);
  5305. VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
  5306. // Update Builder with newly created basic block.
  5307. Builder.SetInsertPoint(InsertPt);
  5308. }
  5309. Instruction *Cloned = Instr->clone();
  5310. if (!IsVoidRetTy)
  5311. Cloned->setName(Instr->getName() + ".cloned");
  5312. // Replace the operands of the cloned instructions with extracted scalars.
  5313. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  5314. Value *Op = Params[op][Part];
  5315. Cloned->setOperand(op, Op);
  5316. }
  5317. // Place the cloned scalar in the new loop.
  5318. Builder.Insert(Cloned);
  5319. // If the original scalar returns a value we need to place it in a vector
  5320. // so that future users will be able to use it.
  5321. if (!IsVoidRetTy)
  5322. VecResults[Part] = Cloned;
  5323. // End if-block.
  5324. if (IfPredicateStore) {
  5325. BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
  5326. LoopVectorBody.push_back(NewIfBlock);
  5327. VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
  5328. Builder.SetInsertPoint(InsertPt);
  5329. Instruction *OldBr = IfBlock->getTerminator();
  5330. BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
  5331. OldBr->eraseFromParent();
  5332. IfBlock = NewIfBlock;
  5333. }
  5334. }
  5335. }
  5336. void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
  5337. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  5338. bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
  5339. return scalarizeInstruction(Instr, IfPredicateStore);
  5340. }
  5341. Value *InnerLoopUnroller::reverseVector(Value *Vec) {
  5342. return Vec;
  5343. }
  5344. Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
  5345. return V;
  5346. }
  5347. Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
  5348. bool Negate) {
  5349. // When unrolling and the VF is 1, we only need to add a simple scalar.
  5350. Type *ITy = Val->getType();
  5351. assert(!ITy->isVectorTy() && "Val must be a scalar");
  5352. Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
  5353. return Builder.CreateAdd(Val, C, "induction");
  5354. }