LoopVectorize.cpp 307 KB

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