LoopVectorize.cpp 449 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811
  1. //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
  10. // and generates target-independent LLVM-IR.
  11. // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
  12. // of instructions in order to estimate the profitability of vectorization.
  13. //
  14. // The loop vectorizer combines consecutive loop iterations into a single
  15. // 'wide' iteration. After this transformation the index is incremented
  16. // by the SIMD vector width, and not by one.
  17. //
  18. // This pass has three parts:
  19. // 1. The main loop pass that drives the different parts.
  20. // 2. LoopVectorizationLegality - A unit that checks for the legality
  21. // of the vectorization.
  22. // 3. InnerLoopVectorizer - A unit that performs the actual
  23. // widening of instructions.
  24. // 4. LoopVectorizationCostModel - A unit that checks for the profitability
  25. // of vectorization. It decides on the optimal vector width, which
  26. // can be one, if vectorization is not profitable.
  27. //
  28. // There is a development effort going on to migrate loop vectorizer to the
  29. // VPlan infrastructure and to introduce outer loop vectorization support (see
  30. // docs/Proposal/VectorizationPlan.rst and
  31. // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
  32. // purpose, we temporarily introduced the VPlan-native vectorization path: an
  33. // alternative vectorization path that is natively implemented on top of the
  34. // VPlan infrastructure. See EnableVPlanNativePath for enabling.
  35. //
  36. //===----------------------------------------------------------------------===//
  37. //
  38. // The reduction-variable vectorization is based on the paper:
  39. // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
  40. //
  41. // Variable uniformity checks are inspired by:
  42. // Karrenberg, R. and Hack, S. Whole Function Vectorization.
  43. //
  44. // The interleaved access vectorization is based on the paper:
  45. // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
  46. // Data for SIMD
  47. //
  48. // Other ideas/concepts are from:
  49. // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
  50. //
  51. // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
  52. // Vectorizing Compilers.
  53. //
  54. //===----------------------------------------------------------------------===//
  55. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  56. #include "LoopVectorizationPlanner.h"
  57. #include "VPRecipeBuilder.h"
  58. #include "VPlan.h"
  59. #include "VPlanHCFGBuilder.h"
  60. #include "VPlanPredicator.h"
  61. #include "VPlanTransforms.h"
  62. #include "llvm/ADT/APInt.h"
  63. #include "llvm/ADT/ArrayRef.h"
  64. #include "llvm/ADT/DenseMap.h"
  65. #include "llvm/ADT/DenseMapInfo.h"
  66. #include "llvm/ADT/Hashing.h"
  67. #include "llvm/ADT/MapVector.h"
  68. #include "llvm/ADT/None.h"
  69. #include "llvm/ADT/Optional.h"
  70. #include "llvm/ADT/STLExtras.h"
  71. #include "llvm/ADT/SmallPtrSet.h"
  72. #include "llvm/ADT/SmallSet.h"
  73. #include "llvm/ADT/SmallVector.h"
  74. #include "llvm/ADT/Statistic.h"
  75. #include "llvm/ADT/StringRef.h"
  76. #include "llvm/ADT/Twine.h"
  77. #include "llvm/ADT/iterator_range.h"
  78. #include "llvm/Analysis/AssumptionCache.h"
  79. #include "llvm/Analysis/BasicAliasAnalysis.h"
  80. #include "llvm/Analysis/BlockFrequencyInfo.h"
  81. #include "llvm/Analysis/CFG.h"
  82. #include "llvm/Analysis/CodeMetrics.h"
  83. #include "llvm/Analysis/DemandedBits.h"
  84. #include "llvm/Analysis/GlobalsModRef.h"
  85. #include "llvm/Analysis/LoopAccessAnalysis.h"
  86. #include "llvm/Analysis/LoopAnalysisManager.h"
  87. #include "llvm/Analysis/LoopInfo.h"
  88. #include "llvm/Analysis/LoopIterator.h"
  89. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  90. #include "llvm/Analysis/ProfileSummaryInfo.h"
  91. #include "llvm/Analysis/ScalarEvolution.h"
  92. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  93. #include "llvm/Analysis/TargetLibraryInfo.h"
  94. #include "llvm/Analysis/TargetTransformInfo.h"
  95. #include "llvm/Analysis/VectorUtils.h"
  96. #include "llvm/IR/Attributes.h"
  97. #include "llvm/IR/BasicBlock.h"
  98. #include "llvm/IR/CFG.h"
  99. #include "llvm/IR/Constant.h"
  100. #include "llvm/IR/Constants.h"
  101. #include "llvm/IR/DataLayout.h"
  102. #include "llvm/IR/DebugInfoMetadata.h"
  103. #include "llvm/IR/DebugLoc.h"
  104. #include "llvm/IR/DerivedTypes.h"
  105. #include "llvm/IR/DiagnosticInfo.h"
  106. #include "llvm/IR/Dominators.h"
  107. #include "llvm/IR/Function.h"
  108. #include "llvm/IR/IRBuilder.h"
  109. #include "llvm/IR/InstrTypes.h"
  110. #include "llvm/IR/Instruction.h"
  111. #include "llvm/IR/Instructions.h"
  112. #include "llvm/IR/IntrinsicInst.h"
  113. #include "llvm/IR/Intrinsics.h"
  114. #include "llvm/IR/LLVMContext.h"
  115. #include "llvm/IR/Metadata.h"
  116. #include "llvm/IR/Module.h"
  117. #include "llvm/IR/Operator.h"
  118. #include "llvm/IR/PatternMatch.h"
  119. #include "llvm/IR/Type.h"
  120. #include "llvm/IR/Use.h"
  121. #include "llvm/IR/User.h"
  122. #include "llvm/IR/Value.h"
  123. #include "llvm/IR/ValueHandle.h"
  124. #include "llvm/IR/Verifier.h"
  125. #include "llvm/InitializePasses.h"
  126. #include "llvm/Pass.h"
  127. #include "llvm/Support/Casting.h"
  128. #include "llvm/Support/CommandLine.h"
  129. #include "llvm/Support/Compiler.h"
  130. #include "llvm/Support/Debug.h"
  131. #include "llvm/Support/ErrorHandling.h"
  132. #include "llvm/Support/InstructionCost.h"
  133. #include "llvm/Support/MathExtras.h"
  134. #include "llvm/Support/raw_ostream.h"
  135. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  136. #include "llvm/Transforms/Utils/InjectTLIMappings.h"
  137. #include "llvm/Transforms/Utils/LoopSimplify.h"
  138. #include "llvm/Transforms/Utils/LoopUtils.h"
  139. #include "llvm/Transforms/Utils/LoopVersioning.h"
  140. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  141. #include "llvm/Transforms/Utils/SizeOpts.h"
  142. #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
  143. #include <algorithm>
  144. #include <cassert>
  145. #include <cstdint>
  146. #include <cstdlib>
  147. #include <functional>
  148. #include <iterator>
  149. #include <limits>
  150. #include <memory>
  151. #include <string>
  152. #include <tuple>
  153. #include <utility>
  154. using namespace llvm;
  155. #define LV_NAME "loop-vectorize"
  156. #define DEBUG_TYPE LV_NAME
  157. #ifndef NDEBUG
  158. const char VerboseDebug[] = DEBUG_TYPE "-verbose";
  159. #endif
  160. /// @{
  161. /// Metadata attribute names
  162. const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
  163. const char LLVMLoopVectorizeFollowupVectorized[] =
  164. "llvm.loop.vectorize.followup_vectorized";
  165. const char LLVMLoopVectorizeFollowupEpilogue[] =
  166. "llvm.loop.vectorize.followup_epilogue";
  167. /// @}
  168. STATISTIC(LoopsVectorized, "Number of loops vectorized");
  169. STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
  170. STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
  171. static cl::opt<bool> EnableEpilogueVectorization(
  172. "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
  173. cl::desc("Enable vectorization of epilogue loops."));
  174. static cl::opt<unsigned> EpilogueVectorizationForceVF(
  175. "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
  176. cl::desc("When epilogue vectorization is enabled, and a value greater than "
  177. "1 is specified, forces the given VF for all applicable epilogue "
  178. "loops."));
  179. static cl::opt<unsigned> EpilogueVectorizationMinVF(
  180. "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
  181. cl::desc("Only loops with vectorization factor equal to or larger than "
  182. "the specified value are considered for epilogue vectorization."));
  183. /// Loops with a known constant trip count below this number are vectorized only
  184. /// if no scalar iteration overheads are incurred.
  185. static cl::opt<unsigned> TinyTripCountVectorThreshold(
  186. "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
  187. cl::desc("Loops with a constant trip count that is smaller than this "
  188. "value are vectorized only if no scalar iteration overheads "
  189. "are incurred."));
  190. static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
  191. "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
  192. cl::desc("The maximum allowed number of runtime memory checks with a "
  193. "vectorize(enable) pragma."));
  194. // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
  195. // that predication is preferred, and this lists all options. I.e., the
  196. // vectorizer will try to fold the tail-loop (epilogue) into the vector body
  197. // and predicate the instructions accordingly. If tail-folding fails, there are
  198. // different fallback strategies depending on these values:
  199. namespace PreferPredicateTy {
  200. enum Option {
  201. ScalarEpilogue = 0,
  202. PredicateElseScalarEpilogue,
  203. PredicateOrDontVectorize
  204. };
  205. } // namespace PreferPredicateTy
  206. static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
  207. "prefer-predicate-over-epilogue",
  208. cl::init(PreferPredicateTy::ScalarEpilogue),
  209. cl::Hidden,
  210. cl::desc("Tail-folding and predication preferences over creating a scalar "
  211. "epilogue loop."),
  212. cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
  213. "scalar-epilogue",
  214. "Don't tail-predicate loops, create scalar epilogue"),
  215. clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
  216. "predicate-else-scalar-epilogue",
  217. "prefer tail-folding, create scalar epilogue if tail "
  218. "folding fails."),
  219. clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
  220. "predicate-dont-vectorize",
  221. "prefers tail-folding, don't attempt vectorization if "
  222. "tail-folding fails.")));
  223. static cl::opt<bool> MaximizeBandwidth(
  224. "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
  225. cl::desc("Maximize bandwidth when selecting vectorization factor which "
  226. "will be determined by the smallest type in loop."));
  227. static cl::opt<bool> EnableInterleavedMemAccesses(
  228. "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  229. cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
  230. /// An interleave-group may need masking if it resides in a block that needs
  231. /// predication, or in order to mask away gaps.
  232. static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
  233. "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  234. cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
  235. static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
  236. "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
  237. cl::desc("We don't interleave loops with a estimated constant trip count "
  238. "below this number"));
  239. static cl::opt<unsigned> ForceTargetNumScalarRegs(
  240. "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
  241. cl::desc("A flag that overrides the target's number of scalar registers."));
  242. static cl::opt<unsigned> ForceTargetNumVectorRegs(
  243. "force-target-num-vector-regs", cl::init(0), cl::Hidden,
  244. cl::desc("A flag that overrides the target's number of vector registers."));
  245. static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
  246. "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
  247. cl::desc("A flag that overrides the target's max interleave factor for "
  248. "scalar loops."));
  249. static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
  250. "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
  251. cl::desc("A flag that overrides the target's max interleave factor for "
  252. "vectorized loops."));
  253. static cl::opt<unsigned> ForceTargetInstructionCost(
  254. "force-target-instruction-cost", cl::init(0), cl::Hidden,
  255. cl::desc("A flag that overrides the target's expected cost for "
  256. "an instruction to a single constant value. Mostly "
  257. "useful for getting consistent testing."));
  258. static cl::opt<bool> ForceTargetSupportsScalableVectors(
  259. "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
  260. cl::desc(
  261. "Pretend that scalable vectors are supported, even if the target does "
  262. "not support them. This flag should only be used for testing."));
  263. static cl::opt<unsigned> SmallLoopCost(
  264. "small-loop-cost", cl::init(20), cl::Hidden,
  265. cl::desc(
  266. "The cost of a loop that is considered 'small' by the interleaver."));
  267. static cl::opt<bool> LoopVectorizeWithBlockFrequency(
  268. "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
  269. cl::desc("Enable the use of the block frequency analysis to access PGO "
  270. "heuristics minimizing code growth in cold regions and being more "
  271. "aggressive in hot regions."));
  272. // Runtime interleave loops for load/store throughput.
  273. static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
  274. "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
  275. cl::desc(
  276. "Enable runtime interleaving until load/store ports are saturated"));
  277. /// Interleave small loops with scalar reductions.
  278. static cl::opt<bool> InterleaveSmallLoopScalarReduction(
  279. "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
  280. cl::desc("Enable interleaving for loops with small iteration counts that "
  281. "contain scalar reductions to expose ILP."));
  282. /// The number of stores in a loop that are allowed to need predication.
  283. static cl::opt<unsigned> NumberOfStoresToPredicate(
  284. "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
  285. cl::desc("Max number of stores to be predicated behind an if."));
  286. static cl::opt<bool> EnableIndVarRegisterHeur(
  287. "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
  288. cl::desc("Count the induction variable only once when interleaving"));
  289. static cl::opt<bool> EnableCondStoresVectorization(
  290. "enable-cond-stores-vec", cl::init(true), cl::Hidden,
  291. cl::desc("Enable if predication of stores during vectorization."));
  292. static cl::opt<unsigned> MaxNestedScalarReductionIC(
  293. "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
  294. cl::desc("The maximum interleave count to use when interleaving a scalar "
  295. "reduction in a nested loop."));
  296. static cl::opt<bool>
  297. PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
  298. cl::Hidden,
  299. cl::desc("Prefer in-loop vector reductions, "
  300. "overriding the targets preference."));
  301. static cl::opt<bool> ForceOrderedReductions(
  302. "force-ordered-reductions", cl::init(false), cl::Hidden,
  303. cl::desc("Enable the vectorisation of loops with in-order (strict) "
  304. "FP reductions"));
  305. static cl::opt<bool> PreferPredicatedReductionSelect(
  306. "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
  307. cl::desc(
  308. "Prefer predicating a reduction operation over an after loop select."));
  309. cl::opt<bool> EnableVPlanNativePath(
  310. "enable-vplan-native-path", cl::init(false), cl::Hidden,
  311. cl::desc("Enable VPlan-native vectorization path with "
  312. "support for outer loop vectorization."));
  313. // FIXME: Remove this switch once we have divergence analysis. Currently we
  314. // assume divergent non-backedge branches when this switch is true.
  315. cl::opt<bool> EnableVPlanPredication(
  316. "enable-vplan-predication", cl::init(false), cl::Hidden,
  317. cl::desc("Enable VPlan-native vectorization path predicator with "
  318. "support for outer loop vectorization."));
  319. // This flag enables the stress testing of the VPlan H-CFG construction in the
  320. // VPlan-native vectorization path. It must be used in conjuction with
  321. // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
  322. // verification of the H-CFGs built.
  323. static cl::opt<bool> VPlanBuildStressTest(
  324. "vplan-build-stress-test", cl::init(false), cl::Hidden,
  325. cl::desc(
  326. "Build VPlan for every supported loop nest in the function and bail "
  327. "out right after the build (stress test the VPlan H-CFG construction "
  328. "in the VPlan-native vectorization path)."));
  329. cl::opt<bool> llvm::EnableLoopInterleaving(
  330. "interleave-loops", cl::init(true), cl::Hidden,
  331. cl::desc("Enable loop interleaving in Loop vectorization passes"));
  332. cl::opt<bool> llvm::EnableLoopVectorization(
  333. "vectorize-loops", cl::init(true), cl::Hidden,
  334. cl::desc("Run the Loop vectorization passes"));
  335. cl::opt<bool> PrintVPlansInDotFormat(
  336. "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
  337. cl::desc("Use dot format instead of plain text when dumping VPlans"));
  338. /// A helper function that returns true if the given type is irregular. The
  339. /// type is irregular if its allocated size doesn't equal the store size of an
  340. /// element of the corresponding vector type.
  341. static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
  342. // Determine if an array of N elements of type Ty is "bitcast compatible"
  343. // with a <N x Ty> vector.
  344. // This is only true if there is no padding between the array elements.
  345. return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
  346. }
  347. /// A helper function that returns the reciprocal of the block probability of
  348. /// predicated blocks. If we return X, we are assuming the predicated block
  349. /// will execute once for every X iterations of the loop header.
  350. ///
  351. /// TODO: We should use actual block probability here, if available. Currently,
  352. /// we always assume predicated blocks have a 50% chance of executing.
  353. static unsigned getReciprocalPredBlockProb() { return 2; }
  354. /// A helper function that returns an integer or floating-point constant with
  355. /// value C.
  356. static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
  357. return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
  358. : ConstantFP::get(Ty, C);
  359. }
  360. /// Returns "best known" trip count for the specified loop \p L as defined by
  361. /// the following procedure:
  362. /// 1) Returns exact trip count if it is known.
  363. /// 2) Returns expected trip count according to profile data if any.
  364. /// 3) Returns upper bound estimate if it is known.
  365. /// 4) Returns None if all of the above failed.
  366. static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
  367. // Check if exact trip count is known.
  368. if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
  369. return ExpectedTC;
  370. // Check if there is an expected trip count available from profile data.
  371. if (LoopVectorizeWithBlockFrequency)
  372. if (auto EstimatedTC = getLoopEstimatedTripCount(L))
  373. return EstimatedTC;
  374. // Check if upper bound estimate is known.
  375. if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
  376. return ExpectedTC;
  377. return None;
  378. }
  379. // Forward declare GeneratedRTChecks.
  380. class GeneratedRTChecks;
  381. namespace llvm {
  382. AnalysisKey ShouldRunExtraVectorPasses::Key;
  383. /// InnerLoopVectorizer vectorizes loops which contain only one basic
  384. /// block to a specified vectorization factor (VF).
  385. /// This class performs the widening of scalars into vectors, or multiple
  386. /// scalars. This class also implements the following features:
  387. /// * It inserts an epilogue loop for handling loops that don't have iteration
  388. /// counts that are known to be a multiple of the vectorization factor.
  389. /// * It handles the code generation for reduction variables.
  390. /// * Scalarization (implementation using scalars) of un-vectorizable
  391. /// instructions.
  392. /// InnerLoopVectorizer does not perform any vectorization-legality
  393. /// checks, and relies on the caller to check for the different legality
  394. /// aspects. The InnerLoopVectorizer relies on the
  395. /// LoopVectorizationLegality class to provide information about the induction
  396. /// and reduction variables that were found to a given vectorization factor.
  397. class InnerLoopVectorizer {
  398. public:
  399. InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  400. LoopInfo *LI, DominatorTree *DT,
  401. const TargetLibraryInfo *TLI,
  402. const TargetTransformInfo *TTI, AssumptionCache *AC,
  403. OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
  404. unsigned UnrollFactor, LoopVectorizationLegality *LVL,
  405. LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
  406. ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
  407. : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
  408. AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
  409. Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
  410. PSI(PSI), RTChecks(RTChecks) {
  411. // Query this against the original loop and save it here because the profile
  412. // of the original loop header may change as the transformation happens.
  413. OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
  414. OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
  415. }
  416. virtual ~InnerLoopVectorizer() = default;
  417. /// Create a new empty loop that will contain vectorized instructions later
  418. /// on, while the old loop will be used as the scalar remainder. Control flow
  419. /// is generated around the vectorized (and scalar epilogue) loops consisting
  420. /// of various checks and bypasses. Return the pre-header block of the new
  421. /// loop and the start value for the canonical induction, if it is != 0. The
  422. /// latter is the case when vectorizing the epilogue loop. In the case of
  423. /// epilogue vectorization, this function is overriden to handle the more
  424. /// complex control flow around the loops.
  425. virtual std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton();
  426. /// Widen a single call instruction within the innermost loop.
  427. void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
  428. VPTransformState &State);
  429. /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
  430. void fixVectorizedLoop(VPTransformState &State);
  431. // Return true if any runtime check is added.
  432. bool areSafetyChecksAdded() { return AddedSafetyChecks; }
  433. /// A type for vectorized values in the new loop. Each value from the
  434. /// original loop, when vectorized, is represented by UF vector values in the
  435. /// new unrolled loop, where UF is the unroll factor.
  436. using VectorParts = SmallVector<Value *, 2>;
  437. /// Vectorize a single first-order recurrence or pointer induction PHINode in
  438. /// a block. This method handles the induction variable canonicalization. It
  439. /// supports both VF = 1 for unrolled loops and arbitrary length vectors.
  440. void widenPHIInstruction(Instruction *PN, VPWidenPHIRecipe *PhiR,
  441. VPTransformState &State);
  442. /// A helper function to scalarize a single Instruction in the innermost loop.
  443. /// Generates a sequence of scalar instances for each lane between \p MinLane
  444. /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
  445. /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
  446. /// Instr's operands.
  447. void scalarizeInstruction(Instruction *Instr, VPReplicateRecipe *RepRecipe,
  448. const VPIteration &Instance, bool IfPredicateInstr,
  449. VPTransformState &State);
  450. /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
  451. /// is provided, the integer induction variable will first be truncated to
  452. /// the corresponding type. \p CanonicalIV is the scalar value generated for
  453. /// the canonical induction variable.
  454. void widenIntOrFpInduction(PHINode *IV, VPWidenIntOrFpInductionRecipe *Def,
  455. VPTransformState &State, Value *CanonicalIV);
  456. /// Construct the vector value of a scalarized value \p V one lane at a time.
  457. void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
  458. VPTransformState &State);
  459. /// Try to vectorize interleaved access group \p Group with the base address
  460. /// given in \p Addr, optionally masking the vector operations if \p
  461. /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
  462. /// values in the vectorized loop.
  463. void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
  464. ArrayRef<VPValue *> VPDefs,
  465. VPTransformState &State, VPValue *Addr,
  466. ArrayRef<VPValue *> StoredValues,
  467. VPValue *BlockInMask = nullptr);
  468. /// Set the debug location in the builder \p Ptr using the debug location in
  469. /// \p V. If \p Ptr is None then it uses the class member's Builder.
  470. void setDebugLocFromInst(const Value *V,
  471. Optional<IRBuilder<> *> CustomBuilder = None);
  472. /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
  473. void fixNonInductionPHIs(VPTransformState &State);
  474. /// Returns true if the reordering of FP operations is not allowed, but we are
  475. /// able to vectorize with strict in-order reductions for the given RdxDesc.
  476. bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc);
  477. /// Create a broadcast instruction. This method generates a broadcast
  478. /// instruction (shuffle) for loop invariant values and for the induction
  479. /// value. If this is the induction variable then we extend it to N, N+1, ...
  480. /// this is needed because each iteration in the loop corresponds to a SIMD
  481. /// element.
  482. virtual Value *getBroadcastInstrs(Value *V);
  483. /// Add metadata from one instruction to another.
  484. ///
  485. /// This includes both the original MDs from \p From and additional ones (\see
  486. /// addNewMetadata). Use this for *newly created* instructions in the vector
  487. /// loop.
  488. void addMetadata(Instruction *To, Instruction *From);
  489. /// Similar to the previous function but it adds the metadata to a
  490. /// vector of instructions.
  491. void addMetadata(ArrayRef<Value *> To, Instruction *From);
  492. // Returns the resume value (bc.merge.rdx) for a reduction as
  493. // generated by fixReduction.
  494. PHINode *getReductionResumeValue(const RecurrenceDescriptor &RdxDesc);
  495. protected:
  496. friend class LoopVectorizationPlanner;
  497. /// A small list of PHINodes.
  498. using PhiVector = SmallVector<PHINode *, 4>;
  499. /// A type for scalarized values in the new loop. Each value from the
  500. /// original loop, when scalarized, is represented by UF x VF scalar values
  501. /// in the new unrolled loop, where UF is the unroll factor and VF is the
  502. /// vectorization factor.
  503. using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
  504. /// Set up the values of the IVs correctly when exiting the vector loop.
  505. void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
  506. Value *CountRoundDown, Value *EndValue,
  507. BasicBlock *MiddleBlock);
  508. /// Introduce a conditional branch (on true, condition to be set later) at the
  509. /// end of the header=latch connecting it to itself (across the backedge) and
  510. /// to the exit block of \p L.
  511. void createHeaderBranch(Loop *L);
  512. /// Handle all cross-iteration phis in the header.
  513. void fixCrossIterationPHIs(VPTransformState &State);
  514. /// Create the exit value of first order recurrences in the middle block and
  515. /// update their users.
  516. void fixFirstOrderRecurrence(VPFirstOrderRecurrencePHIRecipe *PhiR,
  517. VPTransformState &State);
  518. /// Create code for the loop exit value of the reduction.
  519. void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
  520. /// Clear NSW/NUW flags from reduction instructions if necessary.
  521. void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
  522. VPTransformState &State);
  523. /// Fixup the LCSSA phi nodes in the unique exit block. This simply
  524. /// means we need to add the appropriate incoming value from the middle
  525. /// block as exiting edges from the scalar epilogue loop (if present) are
  526. /// already in place, and we exit the vector loop exclusively to the middle
  527. /// block.
  528. void fixLCSSAPHIs(VPTransformState &State);
  529. /// Iteratively sink the scalarized operands of a predicated instruction into
  530. /// the block that was created for it.
  531. void sinkScalarOperands(Instruction *PredInst);
  532. /// Shrinks vector element sizes to the smallest bitwidth they can be legally
  533. /// represented as.
  534. void truncateToMinimalBitwidths(VPTransformState &State);
  535. /// Compute scalar induction steps. \p ScalarIV is the scalar induction
  536. /// variable on which to base the steps, \p Step is the size of the step, and
  537. /// \p EntryVal is the value from the original loop that maps to the steps.
  538. /// Note that \p EntryVal doesn't have to be an induction variable - it
  539. /// can also be a truncate instruction.
  540. void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
  541. const InductionDescriptor &ID, VPValue *Def,
  542. VPTransformState &State);
  543. /// Create a vector induction phi node based on an existing scalar one. \p
  544. /// EntryVal is the value from the original loop that maps to the vector phi
  545. /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
  546. /// truncate instruction, instead of widening the original IV, we widen a
  547. /// version of the IV truncated to \p EntryVal's type.
  548. void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
  549. Value *Step, Value *Start,
  550. Instruction *EntryVal, VPValue *Def,
  551. VPTransformState &State);
  552. /// Returns (and creates if needed) the original loop trip count.
  553. Value *getOrCreateTripCount(Loop *NewLoop);
  554. /// Returns (and creates if needed) the trip count of the widened loop.
  555. Value *getOrCreateVectorTripCount(Loop *NewLoop);
  556. /// Returns a bitcasted value to the requested vector type.
  557. /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
  558. Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
  559. const DataLayout &DL);
  560. /// Emit a bypass check to see if the vector trip count is zero, including if
  561. /// it overflows.
  562. void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
  563. /// Emit a bypass check to see if all of the SCEV assumptions we've
  564. /// had to make are correct. Returns the block containing the checks or
  565. /// nullptr if no checks have been added.
  566. BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
  567. /// Emit bypass checks to check any memory assumptions we may have made.
  568. /// Returns the block containing the checks or nullptr if no checks have been
  569. /// added.
  570. BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
  571. /// Compute the transformed value of Index at offset StartValue using step
  572. /// StepValue.
  573. /// For integer induction, returns StartValue + Index * StepValue.
  574. /// For pointer induction, returns StartValue[Index * StepValue].
  575. /// FIXME: The newly created binary instructions should contain nsw/nuw
  576. /// flags, which can be found from the original scalar operations.
  577. Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
  578. const DataLayout &DL,
  579. const InductionDescriptor &ID,
  580. BasicBlock *VectorHeader) const;
  581. /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
  582. /// vector loop preheader, middle block and scalar preheader. Also
  583. /// allocate a loop object for the new vector loop and return it.
  584. Loop *createVectorLoopSkeleton(StringRef Prefix);
  585. /// Create new phi nodes for the induction variables to resume iteration count
  586. /// in the scalar epilogue, from where the vectorized loop left off.
  587. /// In cases where the loop skeleton is more complicated (eg. epilogue
  588. /// vectorization) and the resume values can come from an additional bypass
  589. /// block, the \p AdditionalBypass pair provides information about the bypass
  590. /// block and the end value on the edge from bypass to this loop.
  591. void createInductionResumeValues(
  592. Loop *L,
  593. std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
  594. /// Complete the loop skeleton by adding debug MDs, creating appropriate
  595. /// conditional branches in the middle block, preparing the builder and
  596. /// running the verifier. Take in the vector loop \p L as argument, and return
  597. /// the preheader of the completed vector loop.
  598. BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
  599. /// Add additional metadata to \p To that was not present on \p Orig.
  600. ///
  601. /// Currently this is used to add the noalias annotations based on the
  602. /// inserted memchecks. Use this for instructions that are *cloned* into the
  603. /// vector loop.
  604. void addNewMetadata(Instruction *To, const Instruction *Orig);
  605. /// Collect poison-generating recipes that may generate a poison value that is
  606. /// used after vectorization, even when their operands are not poison. Those
  607. /// recipes meet the following conditions:
  608. /// * Contribute to the address computation of a recipe generating a widen
  609. /// memory load/store (VPWidenMemoryInstructionRecipe or
  610. /// VPInterleaveRecipe).
  611. /// * Such a widen memory load/store has at least one underlying Instruction
  612. /// that is in a basic block that needs predication and after vectorization
  613. /// the generated instruction won't be predicated.
  614. void collectPoisonGeneratingRecipes(VPTransformState &State);
  615. /// Allow subclasses to override and print debug traces before/after vplan
  616. /// execution, when trace information is requested.
  617. virtual void printDebugTracesAtStart(){};
  618. virtual void printDebugTracesAtEnd(){};
  619. /// The original loop.
  620. Loop *OrigLoop;
  621. /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
  622. /// dynamic knowledge to simplify SCEV expressions and converts them to a
  623. /// more usable form.
  624. PredicatedScalarEvolution &PSE;
  625. /// Loop Info.
  626. LoopInfo *LI;
  627. /// Dominator Tree.
  628. DominatorTree *DT;
  629. /// Alias Analysis.
  630. AAResults *AA;
  631. /// Target Library Info.
  632. const TargetLibraryInfo *TLI;
  633. /// Target Transform Info.
  634. const TargetTransformInfo *TTI;
  635. /// Assumption Cache.
  636. AssumptionCache *AC;
  637. /// Interface to emit optimization remarks.
  638. OptimizationRemarkEmitter *ORE;
  639. /// LoopVersioning. It's only set up (non-null) if memchecks were
  640. /// used.
  641. ///
  642. /// This is currently only used to add no-alias metadata based on the
  643. /// memchecks. The actually versioning is performed manually.
  644. std::unique_ptr<LoopVersioning> LVer;
  645. /// The vectorization SIMD factor to use. Each vector will have this many
  646. /// vector elements.
  647. ElementCount VF;
  648. /// The vectorization unroll factor to use. Each scalar is vectorized to this
  649. /// many different vector instructions.
  650. unsigned UF;
  651. /// The builder that we use
  652. IRBuilder<> Builder;
  653. // --- Vectorization state ---
  654. /// The vector-loop preheader.
  655. BasicBlock *LoopVectorPreHeader;
  656. /// The scalar-loop preheader.
  657. BasicBlock *LoopScalarPreHeader;
  658. /// Middle Block between the vector and the scalar.
  659. BasicBlock *LoopMiddleBlock;
  660. /// The unique ExitBlock of the scalar loop if one exists. Note that
  661. /// there can be multiple exiting edges reaching this block.
  662. BasicBlock *LoopExitBlock;
  663. /// The vector loop body.
  664. BasicBlock *LoopVectorBody;
  665. /// The scalar loop body.
  666. BasicBlock *LoopScalarBody;
  667. /// A list of all bypass blocks. The first block is the entry of the loop.
  668. SmallVector<BasicBlock *, 4> LoopBypassBlocks;
  669. /// Store instructions that were predicated.
  670. SmallVector<Instruction *, 4> PredicatedInstructions;
  671. /// Trip count of the original loop.
  672. Value *TripCount = nullptr;
  673. /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
  674. Value *VectorTripCount = nullptr;
  675. /// The legality analysis.
  676. LoopVectorizationLegality *Legal;
  677. /// The profitablity analysis.
  678. LoopVectorizationCostModel *Cost;
  679. // Record whether runtime checks are added.
  680. bool AddedSafetyChecks = false;
  681. // Holds the end values for each induction variable. We save the end values
  682. // so we can later fix-up the external users of the induction variables.
  683. DenseMap<PHINode *, Value *> IVEndValues;
  684. // Vector of original scalar PHIs whose corresponding widened PHIs need to be
  685. // fixed up at the end of vector code generation.
  686. SmallVector<PHINode *, 8> OrigPHIsToFix;
  687. /// BFI and PSI are used to check for profile guided size optimizations.
  688. BlockFrequencyInfo *BFI;
  689. ProfileSummaryInfo *PSI;
  690. // Whether this loop should be optimized for size based on profile guided size
  691. // optimizatios.
  692. bool OptForSizeBasedOnProfile;
  693. /// Structure to hold information about generated runtime checks, responsible
  694. /// for cleaning the checks, if vectorization turns out unprofitable.
  695. GeneratedRTChecks &RTChecks;
  696. // Holds the resume values for reductions in the loops, used to set the
  697. // correct start value of reduction PHIs when vectorizing the epilogue.
  698. SmallMapVector<const RecurrenceDescriptor *, PHINode *, 4>
  699. ReductionResumeValues;
  700. };
  701. class InnerLoopUnroller : public InnerLoopVectorizer {
  702. public:
  703. InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  704. LoopInfo *LI, DominatorTree *DT,
  705. const TargetLibraryInfo *TLI,
  706. const TargetTransformInfo *TTI, AssumptionCache *AC,
  707. OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
  708. LoopVectorizationLegality *LVL,
  709. LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
  710. ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
  711. : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
  712. ElementCount::getFixed(1), UnrollFactor, LVL, CM,
  713. BFI, PSI, Check) {}
  714. private:
  715. Value *getBroadcastInstrs(Value *V) override;
  716. };
  717. /// Encapsulate information regarding vectorization of a loop and its epilogue.
  718. /// This information is meant to be updated and used across two stages of
  719. /// epilogue vectorization.
  720. struct EpilogueLoopVectorizationInfo {
  721. ElementCount MainLoopVF = ElementCount::getFixed(0);
  722. unsigned MainLoopUF = 0;
  723. ElementCount EpilogueVF = ElementCount::getFixed(0);
  724. unsigned EpilogueUF = 0;
  725. BasicBlock *MainLoopIterationCountCheck = nullptr;
  726. BasicBlock *EpilogueIterationCountCheck = nullptr;
  727. BasicBlock *SCEVSafetyCheck = nullptr;
  728. BasicBlock *MemSafetyCheck = nullptr;
  729. Value *TripCount = nullptr;
  730. Value *VectorTripCount = nullptr;
  731. EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
  732. ElementCount EVF, unsigned EUF)
  733. : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
  734. assert(EUF == 1 &&
  735. "A high UF for the epilogue loop is likely not beneficial.");
  736. }
  737. };
  738. /// An extension of the inner loop vectorizer that creates a skeleton for a
  739. /// vectorized loop that has its epilogue (residual) also vectorized.
  740. /// The idea is to run the vplan on a given loop twice, firstly to setup the
  741. /// skeleton and vectorize the main loop, and secondly to complete the skeleton
  742. /// from the first step and vectorize the epilogue. This is achieved by
  743. /// deriving two concrete strategy classes from this base class and invoking
  744. /// them in succession from the loop vectorizer planner.
  745. class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
  746. public:
  747. InnerLoopAndEpilogueVectorizer(
  748. Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
  749. DominatorTree *DT, const TargetLibraryInfo *TLI,
  750. const TargetTransformInfo *TTI, AssumptionCache *AC,
  751. OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
  752. LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
  753. BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
  754. GeneratedRTChecks &Checks)
  755. : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
  756. EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
  757. Checks),
  758. EPI(EPI) {}
  759. // Override this function to handle the more complex control flow around the
  760. // three loops.
  761. std::pair<BasicBlock *, Value *>
  762. createVectorizedLoopSkeleton() final override {
  763. return createEpilogueVectorizedLoopSkeleton();
  764. }
  765. /// The interface for creating a vectorized skeleton using one of two
  766. /// different strategies, each corresponding to one execution of the vplan
  767. /// as described above.
  768. virtual std::pair<BasicBlock *, Value *>
  769. createEpilogueVectorizedLoopSkeleton() = 0;
  770. /// Holds and updates state information required to vectorize the main loop
  771. /// and its epilogue in two separate passes. This setup helps us avoid
  772. /// regenerating and recomputing runtime safety checks. It also helps us to
  773. /// shorten the iteration-count-check path length for the cases where the
  774. /// iteration count of the loop is so small that the main vector loop is
  775. /// completely skipped.
  776. EpilogueLoopVectorizationInfo &EPI;
  777. };
  778. /// A specialized derived class of inner loop vectorizer that performs
  779. /// vectorization of *main* loops in the process of vectorizing loops and their
  780. /// epilogues.
  781. class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
  782. public:
  783. EpilogueVectorizerMainLoop(
  784. Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
  785. DominatorTree *DT, const TargetLibraryInfo *TLI,
  786. const TargetTransformInfo *TTI, AssumptionCache *AC,
  787. OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
  788. LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
  789. BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
  790. GeneratedRTChecks &Check)
  791. : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
  792. EPI, LVL, CM, BFI, PSI, Check) {}
  793. /// Implements the interface for creating a vectorized skeleton using the
  794. /// *main loop* strategy (ie the first pass of vplan execution).
  795. std::pair<BasicBlock *, Value *>
  796. createEpilogueVectorizedLoopSkeleton() final override;
  797. protected:
  798. /// Emits an iteration count bypass check once for the main loop (when \p
  799. /// ForEpilogue is false) and once for the epilogue loop (when \p
  800. /// ForEpilogue is true).
  801. BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
  802. bool ForEpilogue);
  803. void printDebugTracesAtStart() override;
  804. void printDebugTracesAtEnd() override;
  805. };
  806. // A specialized derived class of inner loop vectorizer that performs
  807. // vectorization of *epilogue* loops in the process of vectorizing loops and
  808. // their epilogues.
  809. class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
  810. public:
  811. EpilogueVectorizerEpilogueLoop(
  812. Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
  813. DominatorTree *DT, const TargetLibraryInfo *TLI,
  814. const TargetTransformInfo *TTI, AssumptionCache *AC,
  815. OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
  816. LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
  817. BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
  818. GeneratedRTChecks &Checks)
  819. : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
  820. EPI, LVL, CM, BFI, PSI, Checks) {}
  821. /// Implements the interface for creating a vectorized skeleton using the
  822. /// *epilogue loop* strategy (ie the second pass of vplan execution).
  823. std::pair<BasicBlock *, Value *>
  824. createEpilogueVectorizedLoopSkeleton() final override;
  825. protected:
  826. /// Emits an iteration count bypass check after the main vector loop has
  827. /// finished to see if there are any iterations left to execute by either
  828. /// the vector epilogue or the scalar epilogue.
  829. BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
  830. BasicBlock *Bypass,
  831. BasicBlock *Insert);
  832. void printDebugTracesAtStart() override;
  833. void printDebugTracesAtEnd() override;
  834. };
  835. } // end namespace llvm
  836. /// Look for a meaningful debug location on the instruction or it's
  837. /// operands.
  838. static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
  839. if (!I)
  840. return I;
  841. DebugLoc Empty;
  842. if (I->getDebugLoc() != Empty)
  843. return I;
  844. for (Use &Op : I->operands()) {
  845. if (Instruction *OpInst = dyn_cast<Instruction>(Op))
  846. if (OpInst->getDebugLoc() != Empty)
  847. return OpInst;
  848. }
  849. return I;
  850. }
  851. void InnerLoopVectorizer::setDebugLocFromInst(
  852. const Value *V, Optional<IRBuilder<> *> CustomBuilder) {
  853. IRBuilder<> *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
  854. if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
  855. const DILocation *DIL = Inst->getDebugLoc();
  856. // When a FSDiscriminator is enabled, we don't need to add the multiply
  857. // factors to the discriminators.
  858. if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
  859. !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
  860. // FIXME: For scalable vectors, assume vscale=1.
  861. auto NewDIL =
  862. DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
  863. if (NewDIL)
  864. B->SetCurrentDebugLocation(NewDIL.getValue());
  865. else
  866. LLVM_DEBUG(dbgs()
  867. << "Failed to create new discriminator: "
  868. << DIL->getFilename() << " Line: " << DIL->getLine());
  869. } else
  870. B->SetCurrentDebugLocation(DIL);
  871. } else
  872. B->SetCurrentDebugLocation(DebugLoc());
  873. }
  874. /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
  875. /// is passed, the message relates to that particular instruction.
  876. #ifndef NDEBUG
  877. static void debugVectorizationMessage(const StringRef Prefix,
  878. const StringRef DebugMsg,
  879. Instruction *I) {
  880. dbgs() << "LV: " << Prefix << DebugMsg;
  881. if (I != nullptr)
  882. dbgs() << " " << *I;
  883. else
  884. dbgs() << '.';
  885. dbgs() << '\n';
  886. }
  887. #endif
  888. /// Create an analysis remark that explains why vectorization failed
  889. ///
  890. /// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
  891. /// RemarkName is the identifier for the remark. If \p I is passed it is an
  892. /// instruction that prevents vectorization. Otherwise \p TheLoop is used for
  893. /// the location of the remark. \return the remark object that can be
  894. /// streamed to.
  895. static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
  896. StringRef RemarkName, Loop *TheLoop, Instruction *I) {
  897. Value *CodeRegion = TheLoop->getHeader();
  898. DebugLoc DL = TheLoop->getStartLoc();
  899. if (I) {
  900. CodeRegion = I->getParent();
  901. // If there is no debug location attached to the instruction, revert back to
  902. // using the loop's.
  903. if (I->getDebugLoc())
  904. DL = I->getDebugLoc();
  905. }
  906. return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
  907. }
  908. namespace llvm {
  909. /// Return a value for Step multiplied by VF.
  910. Value *createStepForVF(IRBuilder<> &B, Type *Ty, ElementCount VF,
  911. int64_t Step) {
  912. assert(Ty->isIntegerTy() && "Expected an integer step");
  913. Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
  914. return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
  915. }
  916. /// Return the runtime value for VF.
  917. Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
  918. Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
  919. return VF.isScalable() ? B.CreateVScale(EC) : EC;
  920. }
  921. static Value *getRuntimeVFAsFloat(IRBuilder<> &B, Type *FTy, ElementCount VF) {
  922. assert(FTy->isFloatingPointTy() && "Expected floating point type!");
  923. Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
  924. Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
  925. return B.CreateUIToFP(RuntimeVF, FTy);
  926. }
  927. void reportVectorizationFailure(const StringRef DebugMsg,
  928. const StringRef OREMsg, const StringRef ORETag,
  929. OptimizationRemarkEmitter *ORE, Loop *TheLoop,
  930. Instruction *I) {
  931. LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
  932. LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
  933. ORE->emit(
  934. createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
  935. << "loop not vectorized: " << OREMsg);
  936. }
  937. void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
  938. OptimizationRemarkEmitter *ORE, Loop *TheLoop,
  939. Instruction *I) {
  940. LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
  941. LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
  942. ORE->emit(
  943. createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
  944. << Msg);
  945. }
  946. } // end namespace llvm
  947. #ifndef NDEBUG
  948. /// \return string containing a file name and a line # for the given loop.
  949. static std::string getDebugLocString(const Loop *L) {
  950. std::string Result;
  951. if (L) {
  952. raw_string_ostream OS(Result);
  953. if (const DebugLoc LoopDbgLoc = L->getStartLoc())
  954. LoopDbgLoc.print(OS);
  955. else
  956. // Just print the module name.
  957. OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
  958. OS.flush();
  959. }
  960. return Result;
  961. }
  962. #endif
  963. void InnerLoopVectorizer::addNewMetadata(Instruction *To,
  964. const Instruction *Orig) {
  965. // If the loop was versioned with memchecks, add the corresponding no-alias
  966. // metadata.
  967. if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
  968. LVer->annotateInstWithNoAlias(To, Orig);
  969. }
  970. void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
  971. VPTransformState &State) {
  972. // Collect recipes in the backward slice of `Root` that may generate a poison
  973. // value that is used after vectorization.
  974. SmallPtrSet<VPRecipeBase *, 16> Visited;
  975. auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
  976. SmallVector<VPRecipeBase *, 16> Worklist;
  977. Worklist.push_back(Root);
  978. // Traverse the backward slice of Root through its use-def chain.
  979. while (!Worklist.empty()) {
  980. VPRecipeBase *CurRec = Worklist.back();
  981. Worklist.pop_back();
  982. if (!Visited.insert(CurRec).second)
  983. continue;
  984. // Prune search if we find another recipe generating a widen memory
  985. // instruction. Widen memory instructions involved in address computation
  986. // will lead to gather/scatter instructions, which don't need to be
  987. // handled.
  988. if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
  989. isa<VPInterleaveRecipe>(CurRec) ||
  990. isa<VPCanonicalIVPHIRecipe>(CurRec))
  991. continue;
  992. // This recipe contributes to the address computation of a widen
  993. // load/store. Collect recipe if its underlying instruction has
  994. // poison-generating flags.
  995. Instruction *Instr = CurRec->getUnderlyingInstr();
  996. if (Instr && Instr->hasPoisonGeneratingFlags())
  997. State.MayGeneratePoisonRecipes.insert(CurRec);
  998. // Add new definitions to the worklist.
  999. for (VPValue *operand : CurRec->operands())
  1000. if (VPDef *OpDef = operand->getDef())
  1001. Worklist.push_back(cast<VPRecipeBase>(OpDef));
  1002. }
  1003. });
  1004. // Traverse all the recipes in the VPlan and collect the poison-generating
  1005. // recipes in the backward slice starting at the address of a VPWidenRecipe or
  1006. // VPInterleaveRecipe.
  1007. auto Iter = depth_first(
  1008. VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
  1009. for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
  1010. for (VPRecipeBase &Recipe : *VPBB) {
  1011. if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
  1012. Instruction *UnderlyingInstr = WidenRec->getUnderlyingInstr();
  1013. VPDef *AddrDef = WidenRec->getAddr()->getDef();
  1014. if (AddrDef && WidenRec->isConsecutive() && UnderlyingInstr &&
  1015. Legal->blockNeedsPredication(UnderlyingInstr->getParent()))
  1016. collectPoisonGeneratingInstrsInBackwardSlice(
  1017. cast<VPRecipeBase>(AddrDef));
  1018. } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
  1019. VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
  1020. if (AddrDef) {
  1021. // Check if any member of the interleave group needs predication.
  1022. const InterleaveGroup<Instruction> *InterGroup =
  1023. InterleaveRec->getInterleaveGroup();
  1024. bool NeedPredication = false;
  1025. for (int I = 0, NumMembers = InterGroup->getNumMembers();
  1026. I < NumMembers; ++I) {
  1027. Instruction *Member = InterGroup->getMember(I);
  1028. if (Member)
  1029. NeedPredication |=
  1030. Legal->blockNeedsPredication(Member->getParent());
  1031. }
  1032. if (NeedPredication)
  1033. collectPoisonGeneratingInstrsInBackwardSlice(
  1034. cast<VPRecipeBase>(AddrDef));
  1035. }
  1036. }
  1037. }
  1038. }
  1039. }
  1040. void InnerLoopVectorizer::addMetadata(Instruction *To,
  1041. Instruction *From) {
  1042. propagateMetadata(To, From);
  1043. addNewMetadata(To, From);
  1044. }
  1045. void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
  1046. Instruction *From) {
  1047. for (Value *V : To) {
  1048. if (Instruction *I = dyn_cast<Instruction>(V))
  1049. addMetadata(I, From);
  1050. }
  1051. }
  1052. PHINode *InnerLoopVectorizer::getReductionResumeValue(
  1053. const RecurrenceDescriptor &RdxDesc) {
  1054. auto It = ReductionResumeValues.find(&RdxDesc);
  1055. assert(It != ReductionResumeValues.end() &&
  1056. "Expected to find a resume value for the reduction.");
  1057. return It->second;
  1058. }
  1059. namespace llvm {
  1060. // Loop vectorization cost-model hints how the scalar epilogue loop should be
  1061. // lowered.
  1062. enum ScalarEpilogueLowering {
  1063. // The default: allowing scalar epilogues.
  1064. CM_ScalarEpilogueAllowed,
  1065. // Vectorization with OptForSize: don't allow epilogues.
  1066. CM_ScalarEpilogueNotAllowedOptSize,
  1067. // A special case of vectorisation with OptForSize: loops with a very small
  1068. // trip count are considered for vectorization under OptForSize, thereby
  1069. // making sure the cost of their loop body is dominant, free of runtime
  1070. // guards and scalar iteration overheads.
  1071. CM_ScalarEpilogueNotAllowedLowTripLoop,
  1072. // Loop hint predicate indicating an epilogue is undesired.
  1073. CM_ScalarEpilogueNotNeededUsePredicate,
  1074. // Directive indicating we must either tail fold or not vectorize
  1075. CM_ScalarEpilogueNotAllowedUsePredicate
  1076. };
  1077. /// ElementCountComparator creates a total ordering for ElementCount
  1078. /// for the purposes of using it in a set structure.
  1079. struct ElementCountComparator {
  1080. bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
  1081. return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
  1082. std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
  1083. }
  1084. };
  1085. using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
  1086. /// LoopVectorizationCostModel - estimates the expected speedups due to
  1087. /// vectorization.
  1088. /// In many cases vectorization is not profitable. This can happen because of
  1089. /// a number of reasons. In this class we mainly attempt to predict the
  1090. /// expected speedup/slowdowns due to the supported instruction set. We use the
  1091. /// TargetTransformInfo to query the different backends for the cost of
  1092. /// different operations.
  1093. class LoopVectorizationCostModel {
  1094. public:
  1095. LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
  1096. PredicatedScalarEvolution &PSE, LoopInfo *LI,
  1097. LoopVectorizationLegality *Legal,
  1098. const TargetTransformInfo &TTI,
  1099. const TargetLibraryInfo *TLI, DemandedBits *DB,
  1100. AssumptionCache *AC,
  1101. OptimizationRemarkEmitter *ORE, const Function *F,
  1102. const LoopVectorizeHints *Hints,
  1103. InterleavedAccessInfo &IAI)
  1104. : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
  1105. TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
  1106. Hints(Hints), InterleaveInfo(IAI) {}
  1107. /// \return An upper bound for the vectorization factors (both fixed and
  1108. /// scalable). If the factors are 0, vectorization and interleaving should be
  1109. /// avoided up front.
  1110. FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
  1111. /// \return True if runtime checks are required for vectorization, and false
  1112. /// otherwise.
  1113. bool runtimeChecksRequired();
  1114. /// \return The most profitable vectorization factor and the cost of that VF.
  1115. /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
  1116. /// then this vectorization factor will be selected if vectorization is
  1117. /// possible.
  1118. VectorizationFactor
  1119. selectVectorizationFactor(const ElementCountSet &CandidateVFs);
  1120. VectorizationFactor
  1121. selectEpilogueVectorizationFactor(const ElementCount MaxVF,
  1122. const LoopVectorizationPlanner &LVP);
  1123. /// Setup cost-based decisions for user vectorization factor.
  1124. /// \return true if the UserVF is a feasible VF to be chosen.
  1125. bool selectUserVectorizationFactor(ElementCount UserVF) {
  1126. collectUniformsAndScalars(UserVF);
  1127. collectInstsToScalarize(UserVF);
  1128. return expectedCost(UserVF).first.isValid();
  1129. }
  1130. /// \return The size (in bits) of the smallest and widest types in the code
  1131. /// that needs to be vectorized. We ignore values that remain scalar such as
  1132. /// 64 bit loop indices.
  1133. std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
  1134. /// \return The desired interleave count.
  1135. /// If interleave count has been specified by metadata it will be returned.
  1136. /// Otherwise, the interleave count is computed and returned. VF and LoopCost
  1137. /// are the selected vectorization factor and the cost of the selected VF.
  1138. unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
  1139. /// Memory access instruction may be vectorized in more than one way.
  1140. /// Form of instruction after vectorization depends on cost.
  1141. /// This function takes cost-based decisions for Load/Store instructions
  1142. /// and collects them in a map. This decisions map is used for building
  1143. /// the lists of loop-uniform and loop-scalar instructions.
  1144. /// The calculated cost is saved with widening decision in order to
  1145. /// avoid redundant calculations.
  1146. void setCostBasedWideningDecision(ElementCount VF);
  1147. /// A struct that represents some properties of the register usage
  1148. /// of a loop.
  1149. struct RegisterUsage {
  1150. /// Holds the number of loop invariant values that are used in the loop.
  1151. /// The key is ClassID of target-provided register class.
  1152. SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
  1153. /// Holds the maximum number of concurrent live intervals in the loop.
  1154. /// The key is ClassID of target-provided register class.
  1155. SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
  1156. };
  1157. /// \return Returns information about the register usages of the loop for the
  1158. /// given vectorization factors.
  1159. SmallVector<RegisterUsage, 8>
  1160. calculateRegisterUsage(ArrayRef<ElementCount> VFs);
  1161. /// Collect values we want to ignore in the cost model.
  1162. void collectValuesToIgnore();
  1163. /// Collect all element types in the loop for which widening is needed.
  1164. void collectElementTypesForWidening();
  1165. /// Split reductions into those that happen in the loop, and those that happen
  1166. /// outside. In loop reductions are collected into InLoopReductionChains.
  1167. void collectInLoopReductions();
  1168. /// Returns true if we should use strict in-order reductions for the given
  1169. /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
  1170. /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
  1171. /// of FP operations.
  1172. bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
  1173. return !Hints->allowReordering() && RdxDesc.isOrdered();
  1174. }
  1175. /// \returns The smallest bitwidth each instruction can be represented with.
  1176. /// The vector equivalents of these instructions should be truncated to this
  1177. /// type.
  1178. const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
  1179. return MinBWs;
  1180. }
  1181. /// \returns True if it is more profitable to scalarize instruction \p I for
  1182. /// vectorization factor \p VF.
  1183. bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
  1184. assert(VF.isVector() &&
  1185. "Profitable to scalarize relevant only for VF > 1.");
  1186. // Cost model is not run in the VPlan-native path - return conservative
  1187. // result until this changes.
  1188. if (EnableVPlanNativePath)
  1189. return false;
  1190. auto Scalars = InstsToScalarize.find(VF);
  1191. assert(Scalars != InstsToScalarize.end() &&
  1192. "VF not yet analyzed for scalarization profitability");
  1193. return Scalars->second.find(I) != Scalars->second.end();
  1194. }
  1195. /// Returns true if \p I is known to be uniform after vectorization.
  1196. bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
  1197. if (VF.isScalar())
  1198. return true;
  1199. // Cost model is not run in the VPlan-native path - return conservative
  1200. // result until this changes.
  1201. if (EnableVPlanNativePath)
  1202. return false;
  1203. auto UniformsPerVF = Uniforms.find(VF);
  1204. assert(UniformsPerVF != Uniforms.end() &&
  1205. "VF not yet analyzed for uniformity");
  1206. return UniformsPerVF->second.count(I);
  1207. }
  1208. /// Returns true if \p I is known to be scalar after vectorization.
  1209. bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
  1210. if (VF.isScalar())
  1211. return true;
  1212. // Cost model is not run in the VPlan-native path - return conservative
  1213. // result until this changes.
  1214. if (EnableVPlanNativePath)
  1215. return false;
  1216. auto ScalarsPerVF = Scalars.find(VF);
  1217. assert(ScalarsPerVF != Scalars.end() &&
  1218. "Scalar values are not calculated for VF");
  1219. return ScalarsPerVF->second.count(I);
  1220. }
  1221. /// \returns True if instruction \p I can be truncated to a smaller bitwidth
  1222. /// for vectorization factor \p VF.
  1223. bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
  1224. return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
  1225. !isProfitableToScalarize(I, VF) &&
  1226. !isScalarAfterVectorization(I, VF);
  1227. }
  1228. /// Decision that was taken during cost calculation for memory instruction.
  1229. enum InstWidening {
  1230. CM_Unknown,
  1231. CM_Widen, // For consecutive accesses with stride +1.
  1232. CM_Widen_Reverse, // For consecutive accesses with stride -1.
  1233. CM_Interleave,
  1234. CM_GatherScatter,
  1235. CM_Scalarize
  1236. };
  1237. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  1238. /// instruction \p I and vector width \p VF.
  1239. void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
  1240. InstructionCost Cost) {
  1241. assert(VF.isVector() && "Expected VF >=2");
  1242. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  1243. }
  1244. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  1245. /// interleaving group \p Grp and vector width \p VF.
  1246. void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
  1247. ElementCount VF, InstWidening W,
  1248. InstructionCost Cost) {
  1249. assert(VF.isVector() && "Expected VF >=2");
  1250. /// Broadcast this decicion to all instructions inside the group.
  1251. /// But the cost will be assigned to one instruction only.
  1252. for (unsigned i = 0; i < Grp->getFactor(); ++i) {
  1253. if (auto *I = Grp->getMember(i)) {
  1254. if (Grp->getInsertPos() == I)
  1255. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  1256. else
  1257. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
  1258. }
  1259. }
  1260. }
  1261. /// Return the cost model decision for the given instruction \p I and vector
  1262. /// width \p VF. Return CM_Unknown if this instruction did not pass
  1263. /// through the cost modeling.
  1264. InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
  1265. assert(VF.isVector() && "Expected VF to be a vector VF");
  1266. // Cost model is not run in the VPlan-native path - return conservative
  1267. // result until this changes.
  1268. if (EnableVPlanNativePath)
  1269. return CM_GatherScatter;
  1270. std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
  1271. auto Itr = WideningDecisions.find(InstOnVF);
  1272. if (Itr == WideningDecisions.end())
  1273. return CM_Unknown;
  1274. return Itr->second.first;
  1275. }
  1276. /// Return the vectorization cost for the given instruction \p I and vector
  1277. /// width \p VF.
  1278. InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
  1279. assert(VF.isVector() && "Expected VF >=2");
  1280. std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
  1281. assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
  1282. "The cost is not calculated");
  1283. return WideningDecisions[InstOnVF].second;
  1284. }
  1285. /// Return True if instruction \p I is an optimizable truncate whose operand
  1286. /// is an induction variable. Such a truncate will be removed by adding a new
  1287. /// induction variable with the destination type.
  1288. bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
  1289. // If the instruction is not a truncate, return false.
  1290. auto *Trunc = dyn_cast<TruncInst>(I);
  1291. if (!Trunc)
  1292. return false;
  1293. // Get the source and destination types of the truncate.
  1294. Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
  1295. Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
  1296. // If the truncate is free for the given types, return false. Replacing a
  1297. // free truncate with an induction variable would add an induction variable
  1298. // update instruction to each iteration of the loop. We exclude from this
  1299. // check the primary induction variable since it will need an update
  1300. // instruction regardless.
  1301. Value *Op = Trunc->getOperand(0);
  1302. if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
  1303. return false;
  1304. // If the truncated value is not an induction variable, return false.
  1305. return Legal->isInductionPhi(Op);
  1306. }
  1307. /// Collects the instructions to scalarize for each predicated instruction in
  1308. /// the loop.
  1309. void collectInstsToScalarize(ElementCount VF);
  1310. /// Collect Uniform and Scalar values for the given \p VF.
  1311. /// The sets depend on CM decision for Load/Store instructions
  1312. /// that may be vectorized as interleave, gather-scatter or scalarized.
  1313. void collectUniformsAndScalars(ElementCount VF) {
  1314. // Do the analysis once.
  1315. if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
  1316. return;
  1317. setCostBasedWideningDecision(VF);
  1318. collectLoopUniforms(VF);
  1319. collectLoopScalars(VF);
  1320. }
  1321. /// Returns true if the target machine supports masked store operation
  1322. /// for the given \p DataType and kind of access to \p Ptr.
  1323. bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
  1324. return Legal->isConsecutivePtr(DataType, Ptr) &&
  1325. TTI.isLegalMaskedStore(DataType, Alignment);
  1326. }
  1327. /// Returns true if the target machine supports masked load operation
  1328. /// for the given \p DataType and kind of access to \p Ptr.
  1329. bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
  1330. return Legal->isConsecutivePtr(DataType, Ptr) &&
  1331. TTI.isLegalMaskedLoad(DataType, Alignment);
  1332. }
  1333. /// Returns true if the target machine can represent \p V as a masked gather
  1334. /// or scatter operation.
  1335. bool isLegalGatherOrScatter(Value *V,
  1336. ElementCount VF = ElementCount::getFixed(1)) {
  1337. bool LI = isa<LoadInst>(V);
  1338. bool SI = isa<StoreInst>(V);
  1339. if (!LI && !SI)
  1340. return false;
  1341. auto *Ty = getLoadStoreType(V);
  1342. Align Align = getLoadStoreAlignment(V);
  1343. if (VF.isVector())
  1344. Ty = VectorType::get(Ty, VF);
  1345. return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
  1346. (SI && TTI.isLegalMaskedScatter(Ty, Align));
  1347. }
  1348. /// Returns true if the target machine supports all of the reduction
  1349. /// variables found for the given VF.
  1350. bool canVectorizeReductions(ElementCount VF) const {
  1351. return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
  1352. const RecurrenceDescriptor &RdxDesc = Reduction.second;
  1353. return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
  1354. }));
  1355. }
  1356. /// Returns true if \p I is an instruction that will be scalarized with
  1357. /// predication when vectorizing \p I with vectorization factor \p VF. Such
  1358. /// instructions include conditional stores and instructions that may divide
  1359. /// by zero.
  1360. bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
  1361. // Returns true if \p I is an instruction that will be predicated either
  1362. // through scalar predication or masked load/store or masked gather/scatter.
  1363. // \p VF is the vectorization factor that will be used to vectorize \p I.
  1364. // Superset of instructions that return true for isScalarWithPredication.
  1365. bool isPredicatedInst(Instruction *I, ElementCount VF,
  1366. bool IsKnownUniform = false) {
  1367. // When we know the load is uniform and the original scalar loop was not
  1368. // predicated we don't need to mark it as a predicated instruction. Any
  1369. // vectorised blocks created when tail-folding are something artificial we
  1370. // have introduced and we know there is always at least one active lane.
  1371. // That's why we call Legal->blockNeedsPredication here because it doesn't
  1372. // query tail-folding.
  1373. if (IsKnownUniform && isa<LoadInst>(I) &&
  1374. !Legal->blockNeedsPredication(I->getParent()))
  1375. return false;
  1376. if (!blockNeedsPredicationForAnyReason(I->getParent()))
  1377. return false;
  1378. // Loads and stores that need some form of masked operation are predicated
  1379. // instructions.
  1380. if (isa<LoadInst>(I) || isa<StoreInst>(I))
  1381. return Legal->isMaskRequired(I);
  1382. return isScalarWithPredication(I, VF);
  1383. }
  1384. /// Returns true if \p I is a memory instruction with consecutive memory
  1385. /// access that can be widened.
  1386. bool
  1387. memoryInstructionCanBeWidened(Instruction *I,
  1388. ElementCount VF = ElementCount::getFixed(1));
  1389. /// Returns true if \p I is a memory instruction in an interleaved-group
  1390. /// of memory accesses that can be vectorized with wide vector loads/stores
  1391. /// and shuffles.
  1392. bool
  1393. interleavedAccessCanBeWidened(Instruction *I,
  1394. ElementCount VF = ElementCount::getFixed(1));
  1395. /// Check if \p Instr belongs to any interleaved access group.
  1396. bool isAccessInterleaved(Instruction *Instr) {
  1397. return InterleaveInfo.isInterleaved(Instr);
  1398. }
  1399. /// Get the interleaved access group that \p Instr belongs to.
  1400. const InterleaveGroup<Instruction> *
  1401. getInterleavedAccessGroup(Instruction *Instr) {
  1402. return InterleaveInfo.getInterleaveGroup(Instr);
  1403. }
  1404. /// Returns true if we're required to use a scalar epilogue for at least
  1405. /// the final iteration of the original loop.
  1406. bool requiresScalarEpilogue(ElementCount VF) const {
  1407. if (!isScalarEpilogueAllowed())
  1408. return false;
  1409. // If we might exit from anywhere but the latch, must run the exiting
  1410. // iteration in scalar form.
  1411. if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
  1412. return true;
  1413. return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
  1414. }
  1415. /// Returns true if a scalar epilogue is not allowed due to optsize or a
  1416. /// loop hint annotation.
  1417. bool isScalarEpilogueAllowed() const {
  1418. return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
  1419. }
  1420. /// Returns true if all loop blocks should be masked to fold tail loop.
  1421. bool foldTailByMasking() const { return FoldTailByMasking; }
  1422. /// Returns true if the instructions in this block requires predication
  1423. /// for any reason, e.g. because tail folding now requires a predicate
  1424. /// or because the block in the original loop was predicated.
  1425. bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
  1426. return foldTailByMasking() || Legal->blockNeedsPredication(BB);
  1427. }
  1428. /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
  1429. /// nodes to the chain of instructions representing the reductions. Uses a
  1430. /// MapVector to ensure deterministic iteration order.
  1431. using ReductionChainMap =
  1432. SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
  1433. /// Return the chain of instructions representing an inloop reduction.
  1434. const ReductionChainMap &getInLoopReductionChains() const {
  1435. return InLoopReductionChains;
  1436. }
  1437. /// Returns true if the Phi is part of an inloop reduction.
  1438. bool isInLoopReduction(PHINode *Phi) const {
  1439. return InLoopReductionChains.count(Phi);
  1440. }
  1441. /// Estimate cost of an intrinsic call instruction CI if it were vectorized
  1442. /// with factor VF. Return the cost of the instruction, including
  1443. /// scalarization overhead if it's needed.
  1444. InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
  1445. /// Estimate cost of a call instruction CI if it were vectorized with factor
  1446. /// VF. Return the cost of the instruction, including scalarization overhead
  1447. /// if it's needed. The flag NeedToScalarize shows if the call needs to be
  1448. /// scalarized -
  1449. /// i.e. either vector version isn't available, or is too expensive.
  1450. InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
  1451. bool &NeedToScalarize) const;
  1452. /// Returns true if the per-lane cost of VectorizationFactor A is lower than
  1453. /// that of B.
  1454. bool isMoreProfitable(const VectorizationFactor &A,
  1455. const VectorizationFactor &B) const;
  1456. /// Invalidates decisions already taken by the cost model.
  1457. void invalidateCostModelingDecisions() {
  1458. WideningDecisions.clear();
  1459. Uniforms.clear();
  1460. Scalars.clear();
  1461. }
  1462. private:
  1463. unsigned NumPredStores = 0;
  1464. /// Convenience function that returns the value of vscale_range iff
  1465. /// vscale_range.min == vscale_range.max or otherwise returns the value
  1466. /// returned by the corresponding TLI method.
  1467. Optional<unsigned> getVScaleForTuning() const;
  1468. /// \return An upper bound for the vectorization factors for both
  1469. /// fixed and scalable vectorization, where the minimum-known number of
  1470. /// elements is a power-of-2 larger than zero. If scalable vectorization is
  1471. /// disabled or unsupported, then the scalable part will be equal to
  1472. /// ElementCount::getScalable(0).
  1473. FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
  1474. ElementCount UserVF,
  1475. bool FoldTailByMasking);
  1476. /// \return the maximized element count based on the targets vector
  1477. /// registers and the loop trip-count, but limited to a maximum safe VF.
  1478. /// This is a helper function of computeFeasibleMaxVF.
  1479. /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
  1480. /// issue that occurred on one of the buildbots which cannot be reproduced
  1481. /// without having access to the properietary compiler (see comments on
  1482. /// D98509). The issue is currently under investigation and this workaround
  1483. /// will be removed as soon as possible.
  1484. ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
  1485. unsigned SmallestType,
  1486. unsigned WidestType,
  1487. const ElementCount &MaxSafeVF,
  1488. bool FoldTailByMasking);
  1489. /// \return the maximum legal scalable VF, based on the safe max number
  1490. /// of elements.
  1491. ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
  1492. /// The vectorization cost is a combination of the cost itself and a boolean
  1493. /// indicating whether any of the contributing operations will actually
  1494. /// operate on vector values after type legalization in the backend. If this
  1495. /// latter value is false, then all operations will be scalarized (i.e. no
  1496. /// vectorization has actually taken place).
  1497. using VectorizationCostTy = std::pair<InstructionCost, bool>;
  1498. /// Returns the expected execution cost. The unit of the cost does
  1499. /// not matter because we use the 'cost' units to compare different
  1500. /// vector widths. The cost that is returned is *not* normalized by
  1501. /// the factor width. If \p Invalid is not nullptr, this function
  1502. /// will add a pair(Instruction*, ElementCount) to \p Invalid for
  1503. /// each instruction that has an Invalid cost for the given VF.
  1504. using InstructionVFPair = std::pair<Instruction *, ElementCount>;
  1505. VectorizationCostTy
  1506. expectedCost(ElementCount VF,
  1507. SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
  1508. /// Returns the execution time cost of an instruction for a given vector
  1509. /// width. Vector width of one means scalar.
  1510. VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
  1511. /// The cost-computation logic from getInstructionCost which provides
  1512. /// the vector type as an output parameter.
  1513. InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
  1514. Type *&VectorTy);
  1515. /// Return the cost of instructions in an inloop reduction pattern, if I is
  1516. /// part of that pattern.
  1517. Optional<InstructionCost>
  1518. getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
  1519. TTI::TargetCostKind CostKind);
  1520. /// Calculate vectorization cost of memory instruction \p I.
  1521. InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
  1522. /// The cost computation for scalarized memory instruction.
  1523. InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
  1524. /// The cost computation for interleaving group of memory instructions.
  1525. InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
  1526. /// The cost computation for Gather/Scatter instruction.
  1527. InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
  1528. /// The cost computation for widening instruction \p I with consecutive
  1529. /// memory access.
  1530. InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
  1531. /// The cost calculation for Load/Store instruction \p I with uniform pointer -
  1532. /// Load: scalar load + broadcast.
  1533. /// Store: scalar store + (loop invariant value stored? 0 : extract of last
  1534. /// element)
  1535. InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
  1536. /// Estimate the overhead of scalarizing an instruction. This is a
  1537. /// convenience wrapper for the type-based getScalarizationOverhead API.
  1538. InstructionCost getScalarizationOverhead(Instruction *I,
  1539. ElementCount VF) const;
  1540. /// Returns whether the instruction is a load or store and will be a emitted
  1541. /// as a vector operation.
  1542. bool isConsecutiveLoadOrStore(Instruction *I);
  1543. /// Returns true if an artificially high cost for emulated masked memrefs
  1544. /// should be used.
  1545. bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
  1546. /// Map of scalar integer values to the smallest bitwidth they can be legally
  1547. /// represented as. The vector equivalents of these values should be truncated
  1548. /// to this type.
  1549. MapVector<Instruction *, uint64_t> MinBWs;
  1550. /// A type representing the costs for instructions if they were to be
  1551. /// scalarized rather than vectorized. The entries are Instruction-Cost
  1552. /// pairs.
  1553. using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
  1554. /// A set containing all BasicBlocks that are known to present after
  1555. /// vectorization as a predicated block.
  1556. SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
  1557. /// Records whether it is allowed to have the original scalar loop execute at
  1558. /// least once. This may be needed as a fallback loop in case runtime
  1559. /// aliasing/dependence checks fail, or to handle the tail/remainder
  1560. /// iterations when the trip count is unknown or doesn't divide by the VF,
  1561. /// or as a peel-loop to handle gaps in interleave-groups.
  1562. /// Under optsize and when the trip count is very small we don't allow any
  1563. /// iterations to execute in the scalar loop.
  1564. ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
  1565. /// All blocks of loop are to be masked to fold tail of scalar iterations.
  1566. bool FoldTailByMasking = false;
  1567. /// A map holding scalar costs for different vectorization factors. The
  1568. /// presence of a cost for an instruction in the mapping indicates that the
  1569. /// instruction will be scalarized when vectorizing with the associated
  1570. /// vectorization factor. The entries are VF-ScalarCostTy pairs.
  1571. DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
  1572. /// Holds the instructions known to be uniform after vectorization.
  1573. /// The data is collected per VF.
  1574. DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
  1575. /// Holds the instructions known to be scalar after vectorization.
  1576. /// The data is collected per VF.
  1577. DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
  1578. /// Holds the instructions (address computations) that are forced to be
  1579. /// scalarized.
  1580. DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
  1581. /// PHINodes of the reductions that should be expanded in-loop along with
  1582. /// their associated chains of reduction operations, in program order from top
  1583. /// (PHI) to bottom
  1584. ReductionChainMap InLoopReductionChains;
  1585. /// A Map of inloop reduction operations and their immediate chain operand.
  1586. /// FIXME: This can be removed once reductions can be costed correctly in
  1587. /// vplan. This was added to allow quick lookup to the inloop operations,
  1588. /// without having to loop through InLoopReductionChains.
  1589. DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
  1590. /// Returns the expected difference in cost from scalarizing the expression
  1591. /// feeding a predicated instruction \p PredInst. The instructions to
  1592. /// scalarize and their scalar costs are collected in \p ScalarCosts. A
  1593. /// non-negative return value implies the expression will be scalarized.
  1594. /// Currently, only single-use chains are considered for scalarization.
  1595. int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
  1596. ElementCount VF);
  1597. /// Collect the instructions that are uniform after vectorization. An
  1598. /// instruction is uniform if we represent it with a single scalar value in
  1599. /// the vectorized loop corresponding to each vector iteration. Examples of
  1600. /// uniform instructions include pointer operands of consecutive or
  1601. /// interleaved memory accesses. Note that although uniformity implies an
  1602. /// instruction will be scalar, the reverse is not true. In general, a
  1603. /// scalarized instruction will be represented by VF scalar values in the
  1604. /// vectorized loop, each corresponding to an iteration of the original
  1605. /// scalar loop.
  1606. void collectLoopUniforms(ElementCount VF);
  1607. /// Collect the instructions that are scalar after vectorization. An
  1608. /// instruction is scalar if it is known to be uniform or will be scalarized
  1609. /// during vectorization. collectLoopScalars should only add non-uniform nodes
  1610. /// to the list if they are used by a load/store instruction that is marked as
  1611. /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
  1612. /// VF values in the vectorized loop, each corresponding to an iteration of
  1613. /// the original scalar loop.
  1614. void collectLoopScalars(ElementCount VF);
  1615. /// Keeps cost model vectorization decision and cost for instructions.
  1616. /// Right now it is used for memory instructions only.
  1617. using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
  1618. std::pair<InstWidening, InstructionCost>>;
  1619. DecisionList WideningDecisions;
  1620. /// Returns true if \p V is expected to be vectorized and it needs to be
  1621. /// extracted.
  1622. bool needsExtract(Value *V, ElementCount VF) const {
  1623. Instruction *I = dyn_cast<Instruction>(V);
  1624. if (VF.isScalar() || !I || !TheLoop->contains(I) ||
  1625. TheLoop->isLoopInvariant(I))
  1626. return false;
  1627. // Assume we can vectorize V (and hence we need extraction) if the
  1628. // scalars are not computed yet. This can happen, because it is called
  1629. // via getScalarizationOverhead from setCostBasedWideningDecision, before
  1630. // the scalars are collected. That should be a safe assumption in most
  1631. // cases, because we check if the operands have vectorizable types
  1632. // beforehand in LoopVectorizationLegality.
  1633. return Scalars.find(VF) == Scalars.end() ||
  1634. !isScalarAfterVectorization(I, VF);
  1635. };
  1636. /// Returns a range containing only operands needing to be extracted.
  1637. SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
  1638. ElementCount VF) const {
  1639. return SmallVector<Value *, 4>(make_filter_range(
  1640. Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
  1641. }
  1642. /// Determines if we have the infrastructure to vectorize loop \p L and its
  1643. /// epilogue, assuming the main loop is vectorized by \p VF.
  1644. bool isCandidateForEpilogueVectorization(const Loop &L,
  1645. const ElementCount VF) const;
  1646. /// Returns true if epilogue vectorization is considered profitable, and
  1647. /// false otherwise.
  1648. /// \p VF is the vectorization factor chosen for the original loop.
  1649. bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
  1650. public:
  1651. /// The loop that we evaluate.
  1652. Loop *TheLoop;
  1653. /// Predicated scalar evolution analysis.
  1654. PredicatedScalarEvolution &PSE;
  1655. /// Loop Info analysis.
  1656. LoopInfo *LI;
  1657. /// Vectorization legality.
  1658. LoopVectorizationLegality *Legal;
  1659. /// Vector target information.
  1660. const TargetTransformInfo &TTI;
  1661. /// Target Library Info.
  1662. const TargetLibraryInfo *TLI;
  1663. /// Demanded bits analysis.
  1664. DemandedBits *DB;
  1665. /// Assumption cache.
  1666. AssumptionCache *AC;
  1667. /// Interface to emit optimization remarks.
  1668. OptimizationRemarkEmitter *ORE;
  1669. const Function *TheFunction;
  1670. /// Loop Vectorize Hint.
  1671. const LoopVectorizeHints *Hints;
  1672. /// The interleave access information contains groups of interleaved accesses
  1673. /// with the same stride and close to each other.
  1674. InterleavedAccessInfo &InterleaveInfo;
  1675. /// Values to ignore in the cost model.
  1676. SmallPtrSet<const Value *, 16> ValuesToIgnore;
  1677. /// Values to ignore in the cost model when VF > 1.
  1678. SmallPtrSet<const Value *, 16> VecValuesToIgnore;
  1679. /// All element types found in the loop.
  1680. SmallPtrSet<Type *, 16> ElementTypesInLoop;
  1681. /// Profitable vector factors.
  1682. SmallVector<VectorizationFactor, 8> ProfitableVFs;
  1683. };
  1684. } // end namespace llvm
  1685. /// Helper struct to manage generating runtime checks for vectorization.
  1686. ///
  1687. /// The runtime checks are created up-front in temporary blocks to allow better
  1688. /// estimating the cost and un-linked from the existing IR. After deciding to
  1689. /// vectorize, the checks are moved back. If deciding not to vectorize, the
  1690. /// temporary blocks are completely removed.
  1691. class GeneratedRTChecks {
  1692. /// Basic block which contains the generated SCEV checks, if any.
  1693. BasicBlock *SCEVCheckBlock = nullptr;
  1694. /// The value representing the result of the generated SCEV checks. If it is
  1695. /// nullptr, either no SCEV checks have been generated or they have been used.
  1696. Value *SCEVCheckCond = nullptr;
  1697. /// Basic block which contains the generated memory runtime checks, if any.
  1698. BasicBlock *MemCheckBlock = nullptr;
  1699. /// The value representing the result of the generated memory runtime checks.
  1700. /// If it is nullptr, either no memory runtime checks have been generated or
  1701. /// they have been used.
  1702. Value *MemRuntimeCheckCond = nullptr;
  1703. DominatorTree *DT;
  1704. LoopInfo *LI;
  1705. SCEVExpander SCEVExp;
  1706. SCEVExpander MemCheckExp;
  1707. public:
  1708. GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
  1709. const DataLayout &DL)
  1710. : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
  1711. MemCheckExp(SE, DL, "scev.check") {}
  1712. /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
  1713. /// accurately estimate the cost of the runtime checks. The blocks are
  1714. /// un-linked from the IR and is added back during vector code generation. If
  1715. /// there is no vector code generation, the check blocks are removed
  1716. /// completely.
  1717. void Create(Loop *L, const LoopAccessInfo &LAI,
  1718. const SCEVUnionPredicate &UnionPred) {
  1719. BasicBlock *LoopHeader = L->getHeader();
  1720. BasicBlock *Preheader = L->getLoopPreheader();
  1721. // Use SplitBlock to create blocks for SCEV & memory runtime checks to
  1722. // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
  1723. // may be used by SCEVExpander. The blocks will be un-linked from their
  1724. // predecessors and removed from LI & DT at the end of the function.
  1725. if (!UnionPred.isAlwaysTrue()) {
  1726. SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
  1727. nullptr, "vector.scevcheck");
  1728. SCEVCheckCond = SCEVExp.expandCodeForPredicate(
  1729. &UnionPred, SCEVCheckBlock->getTerminator());
  1730. }
  1731. const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
  1732. if (RtPtrChecking.Need) {
  1733. auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
  1734. MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
  1735. "vector.memcheck");
  1736. MemRuntimeCheckCond =
  1737. addRuntimeChecks(MemCheckBlock->getTerminator(), L,
  1738. RtPtrChecking.getChecks(), MemCheckExp);
  1739. assert(MemRuntimeCheckCond &&
  1740. "no RT checks generated although RtPtrChecking "
  1741. "claimed checks are required");
  1742. }
  1743. if (!MemCheckBlock && !SCEVCheckBlock)
  1744. return;
  1745. // Unhook the temporary block with the checks, update various places
  1746. // accordingly.
  1747. if (SCEVCheckBlock)
  1748. SCEVCheckBlock->replaceAllUsesWith(Preheader);
  1749. if (MemCheckBlock)
  1750. MemCheckBlock->replaceAllUsesWith(Preheader);
  1751. if (SCEVCheckBlock) {
  1752. SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
  1753. new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
  1754. Preheader->getTerminator()->eraseFromParent();
  1755. }
  1756. if (MemCheckBlock) {
  1757. MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
  1758. new UnreachableInst(Preheader->getContext(), MemCheckBlock);
  1759. Preheader->getTerminator()->eraseFromParent();
  1760. }
  1761. DT->changeImmediateDominator(LoopHeader, Preheader);
  1762. if (MemCheckBlock) {
  1763. DT->eraseNode(MemCheckBlock);
  1764. LI->removeBlock(MemCheckBlock);
  1765. }
  1766. if (SCEVCheckBlock) {
  1767. DT->eraseNode(SCEVCheckBlock);
  1768. LI->removeBlock(SCEVCheckBlock);
  1769. }
  1770. }
  1771. /// Remove the created SCEV & memory runtime check blocks & instructions, if
  1772. /// unused.
  1773. ~GeneratedRTChecks() {
  1774. SCEVExpanderCleaner SCEVCleaner(SCEVExp);
  1775. SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
  1776. if (!SCEVCheckCond)
  1777. SCEVCleaner.markResultUsed();
  1778. if (!MemRuntimeCheckCond)
  1779. MemCheckCleaner.markResultUsed();
  1780. if (MemRuntimeCheckCond) {
  1781. auto &SE = *MemCheckExp.getSE();
  1782. // Memory runtime check generation creates compares that use expanded
  1783. // values. Remove them before running the SCEVExpanderCleaners.
  1784. for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
  1785. if (MemCheckExp.isInsertedInstruction(&I))
  1786. continue;
  1787. SE.forgetValue(&I);
  1788. I.eraseFromParent();
  1789. }
  1790. }
  1791. MemCheckCleaner.cleanup();
  1792. SCEVCleaner.cleanup();
  1793. if (SCEVCheckCond)
  1794. SCEVCheckBlock->eraseFromParent();
  1795. if (MemRuntimeCheckCond)
  1796. MemCheckBlock->eraseFromParent();
  1797. }
  1798. /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
  1799. /// adjusts the branches to branch to the vector preheader or \p Bypass,
  1800. /// depending on the generated condition.
  1801. BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
  1802. BasicBlock *LoopVectorPreHeader,
  1803. BasicBlock *LoopExitBlock) {
  1804. if (!SCEVCheckCond)
  1805. return nullptr;
  1806. if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
  1807. if (C->isZero())
  1808. return nullptr;
  1809. auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
  1810. BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
  1811. // Create new preheader for vector loop.
  1812. if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
  1813. PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
  1814. SCEVCheckBlock->getTerminator()->eraseFromParent();
  1815. SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
  1816. Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
  1817. SCEVCheckBlock);
  1818. DT->addNewBlock(SCEVCheckBlock, Pred);
  1819. DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
  1820. ReplaceInstWithInst(
  1821. SCEVCheckBlock->getTerminator(),
  1822. BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
  1823. // Mark the check as used, to prevent it from being removed during cleanup.
  1824. SCEVCheckCond = nullptr;
  1825. return SCEVCheckBlock;
  1826. }
  1827. /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
  1828. /// the branches to branch to the vector preheader or \p Bypass, depending on
  1829. /// the generated condition.
  1830. BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
  1831. BasicBlock *LoopVectorPreHeader) {
  1832. // Check if we generated code that checks in runtime if arrays overlap.
  1833. if (!MemRuntimeCheckCond)
  1834. return nullptr;
  1835. auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
  1836. Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
  1837. MemCheckBlock);
  1838. DT->addNewBlock(MemCheckBlock, Pred);
  1839. DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
  1840. MemCheckBlock->moveBefore(LoopVectorPreHeader);
  1841. if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
  1842. PL->addBasicBlockToLoop(MemCheckBlock, *LI);
  1843. ReplaceInstWithInst(
  1844. MemCheckBlock->getTerminator(),
  1845. BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
  1846. MemCheckBlock->getTerminator()->setDebugLoc(
  1847. Pred->getTerminator()->getDebugLoc());
  1848. // Mark the check as used, to prevent it from being removed during cleanup.
  1849. MemRuntimeCheckCond = nullptr;
  1850. return MemCheckBlock;
  1851. }
  1852. };
  1853. // Return true if \p OuterLp is an outer loop annotated with hints for explicit
  1854. // vectorization. The loop needs to be annotated with #pragma omp simd
  1855. // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
  1856. // vector length information is not provided, vectorization is not considered
  1857. // explicit. Interleave hints are not allowed either. These limitations will be
  1858. // relaxed in the future.
  1859. // Please, note that we are currently forced to abuse the pragma 'clang
  1860. // vectorize' semantics. This pragma provides *auto-vectorization hints*
  1861. // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
  1862. // provides *explicit vectorization hints* (LV can bypass legal checks and
  1863. // assume that vectorization is legal). However, both hints are implemented
  1864. // using the same metadata (llvm.loop.vectorize, processed by
  1865. // LoopVectorizeHints). This will be fixed in the future when the native IR
  1866. // representation for pragma 'omp simd' is introduced.
  1867. static bool isExplicitVecOuterLoop(Loop *OuterLp,
  1868. OptimizationRemarkEmitter *ORE) {
  1869. assert(!OuterLp->isInnermost() && "This is not an outer loop");
  1870. LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
  1871. // Only outer loops with an explicit vectorization hint are supported.
  1872. // Unannotated outer loops are ignored.
  1873. if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
  1874. return false;
  1875. Function *Fn = OuterLp->getHeader()->getParent();
  1876. if (!Hints.allowVectorization(Fn, OuterLp,
  1877. true /*VectorizeOnlyWhenForced*/)) {
  1878. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
  1879. return false;
  1880. }
  1881. if (Hints.getInterleave() > 1) {
  1882. // TODO: Interleave support is future work.
  1883. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
  1884. "outer loops.\n");
  1885. Hints.emitRemarkWithHints();
  1886. return false;
  1887. }
  1888. return true;
  1889. }
  1890. static void collectSupportedLoops(Loop &L, LoopInfo *LI,
  1891. OptimizationRemarkEmitter *ORE,
  1892. SmallVectorImpl<Loop *> &V) {
  1893. // Collect inner loops and outer loops without irreducible control flow. For
  1894. // now, only collect outer loops that have explicit vectorization hints. If we
  1895. // are stress testing the VPlan H-CFG construction, we collect the outermost
  1896. // loop of every loop nest.
  1897. if (L.isInnermost() || VPlanBuildStressTest ||
  1898. (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
  1899. LoopBlocksRPO RPOT(&L);
  1900. RPOT.perform(LI);
  1901. if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
  1902. V.push_back(&L);
  1903. // TODO: Collect inner loops inside marked outer loops in case
  1904. // vectorization fails for the outer loop. Do not invoke
  1905. // 'containsIrreducibleCFG' again for inner loops when the outer loop is
  1906. // already known to be reducible. We can use an inherited attribute for
  1907. // that.
  1908. return;
  1909. }
  1910. }
  1911. for (Loop *InnerL : L)
  1912. collectSupportedLoops(*InnerL, LI, ORE, V);
  1913. }
  1914. namespace {
  1915. /// The LoopVectorize Pass.
  1916. struct LoopVectorize : public FunctionPass {
  1917. /// Pass identification, replacement for typeid
  1918. static char ID;
  1919. LoopVectorizePass Impl;
  1920. explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
  1921. bool VectorizeOnlyWhenForced = false)
  1922. : FunctionPass(ID),
  1923. Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
  1924. initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
  1925. }
  1926. bool runOnFunction(Function &F) override {
  1927. if (skipFunction(F))
  1928. return false;
  1929. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  1930. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1931. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1932. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1933. auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
  1934. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  1935. auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
  1936. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  1937. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1938. auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
  1939. auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  1940. auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  1941. auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  1942. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  1943. [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
  1944. return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
  1945. GetLAA, *ORE, PSI).MadeAnyChange;
  1946. }
  1947. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1948. AU.addRequired<AssumptionCacheTracker>();
  1949. AU.addRequired<BlockFrequencyInfoWrapperPass>();
  1950. AU.addRequired<DominatorTreeWrapperPass>();
  1951. AU.addRequired<LoopInfoWrapperPass>();
  1952. AU.addRequired<ScalarEvolutionWrapperPass>();
  1953. AU.addRequired<TargetTransformInfoWrapperPass>();
  1954. AU.addRequired<AAResultsWrapperPass>();
  1955. AU.addRequired<LoopAccessLegacyAnalysis>();
  1956. AU.addRequired<DemandedBitsWrapperPass>();
  1957. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  1958. AU.addRequired<InjectTLIMappingsLegacy>();
  1959. // We currently do not preserve loopinfo/dominator analyses with outer loop
  1960. // vectorization. Until this is addressed, mark these analyses as preserved
  1961. // only for non-VPlan-native path.
  1962. // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
  1963. if (!EnableVPlanNativePath) {
  1964. AU.addPreserved<LoopInfoWrapperPass>();
  1965. AU.addPreserved<DominatorTreeWrapperPass>();
  1966. }
  1967. AU.addPreserved<BasicAAWrapperPass>();
  1968. AU.addPreserved<GlobalsAAWrapperPass>();
  1969. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  1970. }
  1971. };
  1972. } // end anonymous namespace
  1973. //===----------------------------------------------------------------------===//
  1974. // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
  1975. // LoopVectorizationCostModel and LoopVectorizationPlanner.
  1976. //===----------------------------------------------------------------------===//
  1977. Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
  1978. // We need to place the broadcast of invariant variables outside the loop,
  1979. // but only if it's proven safe to do so. Else, broadcast will be inside
  1980. // vector loop body.
  1981. Instruction *Instr = dyn_cast<Instruction>(V);
  1982. bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
  1983. (!Instr ||
  1984. DT->dominates(Instr->getParent(), LoopVectorPreHeader));
  1985. // Place the code for broadcasting invariant variables in the new preheader.
  1986. IRBuilder<>::InsertPointGuard Guard(Builder);
  1987. if (SafeToHoist)
  1988. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1989. // Broadcast the scalar into all locations in the vector.
  1990. Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
  1991. return Shuf;
  1992. }
  1993. /// This function adds
  1994. /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
  1995. /// to each vector element of Val. The sequence starts at StartIndex.
  1996. /// \p Opcode is relevant for FP induction variable.
  1997. static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
  1998. Instruction::BinaryOps BinOp, ElementCount VF,
  1999. IRBuilder<> &Builder) {
  2000. assert(VF.isVector() && "only vector VFs are supported");
  2001. // Create and check the types.
  2002. auto *ValVTy = cast<VectorType>(Val->getType());
  2003. ElementCount VLen = ValVTy->getElementCount();
  2004. Type *STy = Val->getType()->getScalarType();
  2005. assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
  2006. "Induction Step must be an integer or FP");
  2007. assert(Step->getType() == STy && "Step has wrong type");
  2008. SmallVector<Constant *, 8> Indices;
  2009. // Create a vector of consecutive numbers from zero to VF.
  2010. VectorType *InitVecValVTy = ValVTy;
  2011. Type *InitVecValSTy = STy;
  2012. if (STy->isFloatingPointTy()) {
  2013. InitVecValSTy =
  2014. IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
  2015. InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
  2016. }
  2017. Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
  2018. // Splat the StartIdx
  2019. Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
  2020. if (STy->isIntegerTy()) {
  2021. InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
  2022. Step = Builder.CreateVectorSplat(VLen, Step);
  2023. assert(Step->getType() == Val->getType() && "Invalid step vec");
  2024. // FIXME: The newly created binary instructions should contain nsw/nuw
  2025. // flags, which can be found from the original scalar operations.
  2026. Step = Builder.CreateMul(InitVec, Step);
  2027. return Builder.CreateAdd(Val, Step, "induction");
  2028. }
  2029. // Floating point induction.
  2030. assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
  2031. "Binary Opcode should be specified for FP induction");
  2032. InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
  2033. InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
  2034. Step = Builder.CreateVectorSplat(VLen, Step);
  2035. Value *MulOp = Builder.CreateFMul(InitVec, Step);
  2036. return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
  2037. }
  2038. void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
  2039. const InductionDescriptor &II, Value *Step, Value *Start,
  2040. Instruction *EntryVal, VPValue *Def, VPTransformState &State) {
  2041. IRBuilder<> &Builder = State.Builder;
  2042. assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
  2043. "Expected either an induction phi-node or a truncate of it!");
  2044. // Construct the initial value of the vector IV in the vector loop preheader
  2045. auto CurrIP = Builder.saveIP();
  2046. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  2047. if (isa<TruncInst>(EntryVal)) {
  2048. assert(Start->getType()->isIntegerTy() &&
  2049. "Truncation requires an integer type");
  2050. auto *TruncType = cast<IntegerType>(EntryVal->getType());
  2051. Step = Builder.CreateTrunc(Step, TruncType);
  2052. Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
  2053. }
  2054. Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
  2055. Value *SplatStart = Builder.CreateVectorSplat(State.VF, Start);
  2056. Value *SteppedStart = getStepVector(
  2057. SplatStart, Zero, Step, II.getInductionOpcode(), State.VF, State.Builder);
  2058. // We create vector phi nodes for both integer and floating-point induction
  2059. // variables. Here, we determine the kind of arithmetic we will perform.
  2060. Instruction::BinaryOps AddOp;
  2061. Instruction::BinaryOps MulOp;
  2062. if (Step->getType()->isIntegerTy()) {
  2063. AddOp = Instruction::Add;
  2064. MulOp = Instruction::Mul;
  2065. } else {
  2066. AddOp = II.getInductionOpcode();
  2067. MulOp = Instruction::FMul;
  2068. }
  2069. // Multiply the vectorization factor by the step using integer or
  2070. // floating-point arithmetic as appropriate.
  2071. Type *StepType = Step->getType();
  2072. Value *RuntimeVF;
  2073. if (Step->getType()->isFloatingPointTy())
  2074. RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, State.VF);
  2075. else
  2076. RuntimeVF = getRuntimeVF(Builder, StepType, State.VF);
  2077. Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
  2078. // Create a vector splat to use in the induction update.
  2079. //
  2080. // FIXME: If the step is non-constant, we create the vector splat with
  2081. // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
  2082. // handle a constant vector splat.
  2083. Value *SplatVF = isa<Constant>(Mul)
  2084. ? ConstantVector::getSplat(State.VF, cast<Constant>(Mul))
  2085. : Builder.CreateVectorSplat(State.VF, Mul);
  2086. Builder.restoreIP(CurrIP);
  2087. // We may need to add the step a number of times, depending on the unroll
  2088. // factor. The last of those goes into the PHI.
  2089. PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
  2090. &*LoopVectorBody->getFirstInsertionPt());
  2091. VecInd->setDebugLoc(EntryVal->getDebugLoc());
  2092. Instruction *LastInduction = VecInd;
  2093. for (unsigned Part = 0; Part < UF; ++Part) {
  2094. State.set(Def, LastInduction, Part);
  2095. if (isa<TruncInst>(EntryVal))
  2096. addMetadata(LastInduction, EntryVal);
  2097. LastInduction = cast<Instruction>(
  2098. Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
  2099. LastInduction->setDebugLoc(EntryVal->getDebugLoc());
  2100. }
  2101. // Move the last step to the end of the latch block. This ensures consistent
  2102. // placement of all induction updates.
  2103. auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
  2104. auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
  2105. LastInduction->moveBefore(Br);
  2106. LastInduction->setName("vec.ind.next");
  2107. VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
  2108. VecInd->addIncoming(LastInduction, LoopVectorLatch);
  2109. }
  2110. void InnerLoopVectorizer::widenIntOrFpInduction(
  2111. PHINode *IV, VPWidenIntOrFpInductionRecipe *Def, VPTransformState &State,
  2112. Value *CanonicalIV) {
  2113. Value *Start = Def->getStartValue()->getLiveInIRValue();
  2114. const InductionDescriptor &ID = Def->getInductionDescriptor();
  2115. TruncInst *Trunc = Def->getTruncInst();
  2116. IRBuilder<> &Builder = State.Builder;
  2117. assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
  2118. assert(!State.VF.isZero() && "VF must be non-zero");
  2119. // The value from the original loop to which we are mapping the new induction
  2120. // variable.
  2121. Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
  2122. auto &DL = EntryVal->getModule()->getDataLayout();
  2123. // Generate code for the induction step. Note that induction steps are
  2124. // required to be loop-invariant
  2125. auto CreateStepValue = [&](const SCEV *Step) -> Value * {
  2126. assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
  2127. "Induction step should be loop invariant");
  2128. if (PSE.getSE()->isSCEVable(IV->getType())) {
  2129. SCEVExpander Exp(*PSE.getSE(), DL, "induction");
  2130. return Exp.expandCodeFor(Step, Step->getType(),
  2131. State.CFG.VectorPreHeader->getTerminator());
  2132. }
  2133. return cast<SCEVUnknown>(Step)->getValue();
  2134. };
  2135. // The scalar value to broadcast. This is derived from the canonical
  2136. // induction variable. If a truncation type is given, truncate the canonical
  2137. // induction variable and step. Otherwise, derive these values from the
  2138. // induction descriptor.
  2139. auto CreateScalarIV = [&](Value *&Step) -> Value * {
  2140. Value *ScalarIV = CanonicalIV;
  2141. Type *NeededType = IV->getType();
  2142. if (!Def->isCanonical() || ScalarIV->getType() != NeededType) {
  2143. ScalarIV =
  2144. NeededType->isIntegerTy()
  2145. ? Builder.CreateSExtOrTrunc(ScalarIV, NeededType)
  2146. : Builder.CreateCast(Instruction::SIToFP, ScalarIV, NeededType);
  2147. ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID,
  2148. State.CFG.PrevBB);
  2149. ScalarIV->setName("offset.idx");
  2150. }
  2151. if (Trunc) {
  2152. auto *TruncType = cast<IntegerType>(Trunc->getType());
  2153. assert(Step->getType()->isIntegerTy() &&
  2154. "Truncation requires an integer step");
  2155. ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
  2156. Step = Builder.CreateTrunc(Step, TruncType);
  2157. }
  2158. return ScalarIV;
  2159. };
  2160. // Fast-math-flags propagate from the original induction instruction.
  2161. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  2162. if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
  2163. Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
  2164. // Now do the actual transformations, and start with creating the step value.
  2165. Value *Step = CreateStepValue(ID.getStep());
  2166. if (State.VF.isScalar()) {
  2167. Value *ScalarIV = CreateScalarIV(Step);
  2168. Type *ScalarTy = IntegerType::get(ScalarIV->getContext(),
  2169. Step->getType()->getScalarSizeInBits());
  2170. for (unsigned Part = 0; Part < UF; ++Part) {
  2171. Value *StartIdx = ConstantInt::get(ScalarTy, Part);
  2172. Value *EntryPart;
  2173. if (Step->getType()->isFloatingPointTy()) {
  2174. StartIdx = Builder.CreateUIToFP(StartIdx, Step->getType());
  2175. Value *MulOp = Builder.CreateFMul(StartIdx, Step);
  2176. EntryPart = Builder.CreateBinOp(ID.getInductionOpcode(), ScalarIV,
  2177. MulOp, "induction");
  2178. } else {
  2179. EntryPart = Builder.CreateAdd(
  2180. ScalarIV, Builder.CreateMul(StartIdx, Step), "induction");
  2181. }
  2182. State.set(Def, EntryPart, Part);
  2183. if (Trunc) {
  2184. assert(!Step->getType()->isFloatingPointTy() &&
  2185. "fp inductions shouldn't be truncated");
  2186. addMetadata(EntryPart, Trunc);
  2187. }
  2188. }
  2189. return;
  2190. }
  2191. // Create a new independent vector induction variable, if one is needed.
  2192. if (Def->needsVectorIV())
  2193. createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, State);
  2194. if (Def->needsScalarIV()) {
  2195. // Create scalar steps that can be used by instructions we will later
  2196. // scalarize. Note that the addition of the scalar steps will not increase
  2197. // the number of instructions in the loop in the common case prior to
  2198. // InstCombine. We will be trading one vector extract for each scalar step.
  2199. Value *ScalarIV = CreateScalarIV(Step);
  2200. buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, State);
  2201. }
  2202. }
  2203. void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
  2204. Instruction *EntryVal,
  2205. const InductionDescriptor &ID,
  2206. VPValue *Def,
  2207. VPTransformState &State) {
  2208. IRBuilder<> &Builder = State.Builder;
  2209. // We shouldn't have to build scalar steps if we aren't vectorizing.
  2210. assert(State.VF.isVector() && "VF should be greater than one");
  2211. // Get the value type and ensure it and the step have the same integer type.
  2212. Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
  2213. assert(ScalarIVTy == Step->getType() &&
  2214. "Val and Step should have the same type");
  2215. // We build scalar steps for both integer and floating-point induction
  2216. // variables. Here, we determine the kind of arithmetic we will perform.
  2217. Instruction::BinaryOps AddOp;
  2218. Instruction::BinaryOps MulOp;
  2219. if (ScalarIVTy->isIntegerTy()) {
  2220. AddOp = Instruction::Add;
  2221. MulOp = Instruction::Mul;
  2222. } else {
  2223. AddOp = ID.getInductionOpcode();
  2224. MulOp = Instruction::FMul;
  2225. }
  2226. // Determine the number of scalars we need to generate for each unroll
  2227. // iteration.
  2228. bool FirstLaneOnly = vputils::onlyFirstLaneUsed(Def);
  2229. unsigned Lanes = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
  2230. // Compute the scalar steps and save the results in State.
  2231. Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
  2232. ScalarIVTy->getScalarSizeInBits());
  2233. Type *VecIVTy = nullptr;
  2234. Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
  2235. if (!FirstLaneOnly && State.VF.isScalable()) {
  2236. VecIVTy = VectorType::get(ScalarIVTy, State.VF);
  2237. UnitStepVec =
  2238. Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
  2239. SplatStep = Builder.CreateVectorSplat(State.VF, Step);
  2240. SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
  2241. }
  2242. for (unsigned Part = 0; Part < State.UF; ++Part) {
  2243. Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
  2244. if (!FirstLaneOnly && State.VF.isScalable()) {
  2245. auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
  2246. auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
  2247. if (ScalarIVTy->isFloatingPointTy())
  2248. InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
  2249. auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
  2250. auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
  2251. State.set(Def, Add, Part);
  2252. // It's useful to record the lane values too for the known minimum number
  2253. // of elements so we do those below. This improves the code quality when
  2254. // trying to extract the first element, for example.
  2255. }
  2256. if (ScalarIVTy->isFloatingPointTy())
  2257. StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
  2258. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  2259. Value *StartIdx = Builder.CreateBinOp(
  2260. AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
  2261. // The step returned by `createStepForVF` is a runtime-evaluated value
  2262. // when VF is scalable. Otherwise, it should be folded into a Constant.
  2263. assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
  2264. "Expected StartIdx to be folded to a constant when VF is not "
  2265. "scalable");
  2266. auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
  2267. auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
  2268. State.set(Def, Add, VPIteration(Part, Lane));
  2269. }
  2270. }
  2271. }
  2272. void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
  2273. const VPIteration &Instance,
  2274. VPTransformState &State) {
  2275. Value *ScalarInst = State.get(Def, Instance);
  2276. Value *VectorValue = State.get(Def, Instance.Part);
  2277. VectorValue = Builder.CreateInsertElement(
  2278. VectorValue, ScalarInst,
  2279. Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
  2280. State.set(Def, VectorValue, Instance.Part);
  2281. }
  2282. // Return whether we allow using masked interleave-groups (for dealing with
  2283. // strided loads/stores that reside in predicated blocks, or for dealing
  2284. // with gaps).
  2285. static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
  2286. // If an override option has been passed in for interleaved accesses, use it.
  2287. if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
  2288. return EnableMaskedInterleavedMemAccesses;
  2289. return TTI.enableMaskedInterleavedAccessVectorization();
  2290. }
  2291. // Try to vectorize the interleave group that \p Instr belongs to.
  2292. //
  2293. // E.g. Translate following interleaved load group (factor = 3):
  2294. // for (i = 0; i < N; i+=3) {
  2295. // R = Pic[i]; // Member of index 0
  2296. // G = Pic[i+1]; // Member of index 1
  2297. // B = Pic[i+2]; // Member of index 2
  2298. // ... // do something to R, G, B
  2299. // }
  2300. // To:
  2301. // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
  2302. // %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
  2303. // %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
  2304. // %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
  2305. //
  2306. // Or translate following interleaved store group (factor = 3):
  2307. // for (i = 0; i < N; i+=3) {
  2308. // ... do something to R, G, B
  2309. // Pic[i] = R; // Member of index 0
  2310. // Pic[i+1] = G; // Member of index 1
  2311. // Pic[i+2] = B; // Member of index 2
  2312. // }
  2313. // To:
  2314. // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
  2315. // %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
  2316. // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
  2317. // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
  2318. // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
  2319. void InnerLoopVectorizer::vectorizeInterleaveGroup(
  2320. const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
  2321. VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
  2322. VPValue *BlockInMask) {
  2323. Instruction *Instr = Group->getInsertPos();
  2324. const DataLayout &DL = Instr->getModule()->getDataLayout();
  2325. // Prepare for the vector type of the interleaved load/store.
  2326. Type *ScalarTy = getLoadStoreType(Instr);
  2327. unsigned InterleaveFactor = Group->getFactor();
  2328. assert(!VF.isScalable() && "scalable vectors not yet supported.");
  2329. auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
  2330. // Prepare for the new pointers.
  2331. SmallVector<Value *, 2> AddrParts;
  2332. unsigned Index = Group->getIndex(Instr);
  2333. // TODO: extend the masked interleaved-group support to reversed access.
  2334. assert((!BlockInMask || !Group->isReverse()) &&
  2335. "Reversed masked interleave-group not supported.");
  2336. // If the group is reverse, adjust the index to refer to the last vector lane
  2337. // instead of the first. We adjust the index from the first vector lane,
  2338. // rather than directly getting the pointer for lane VF - 1, because the
  2339. // pointer operand of the interleaved access is supposed to be uniform. For
  2340. // uniform instructions, we're only required to generate a value for the
  2341. // first vector lane in each unroll iteration.
  2342. if (Group->isReverse())
  2343. Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
  2344. for (unsigned Part = 0; Part < UF; Part++) {
  2345. Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
  2346. setDebugLocFromInst(AddrPart);
  2347. // Notice current instruction could be any index. Need to adjust the address
  2348. // to the member of index 0.
  2349. //
  2350. // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
  2351. // b = A[i]; // Member of index 0
  2352. // Current pointer is pointed to A[i+1], adjust it to A[i].
  2353. //
  2354. // E.g. A[i+1] = a; // Member of index 1
  2355. // A[i] = b; // Member of index 0
  2356. // A[i+2] = c; // Member of index 2 (Current instruction)
  2357. // Current pointer is pointed to A[i+2], adjust it to A[i].
  2358. bool InBounds = false;
  2359. if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
  2360. InBounds = gep->isInBounds();
  2361. AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
  2362. cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
  2363. // Cast to the vector pointer type.
  2364. unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
  2365. Type *PtrTy = VecTy->getPointerTo(AddressSpace);
  2366. AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
  2367. }
  2368. setDebugLocFromInst(Instr);
  2369. Value *PoisonVec = PoisonValue::get(VecTy);
  2370. Value *MaskForGaps = nullptr;
  2371. if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
  2372. MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
  2373. assert(MaskForGaps && "Mask for Gaps is required but it is null");
  2374. }
  2375. // Vectorize the interleaved load group.
  2376. if (isa<LoadInst>(Instr)) {
  2377. // For each unroll part, create a wide load for the group.
  2378. SmallVector<Value *, 2> NewLoads;
  2379. for (unsigned Part = 0; Part < UF; Part++) {
  2380. Instruction *NewLoad;
  2381. if (BlockInMask || MaskForGaps) {
  2382. assert(useMaskedInterleavedAccesses(*TTI) &&
  2383. "masked interleaved groups are not allowed.");
  2384. Value *GroupMask = MaskForGaps;
  2385. if (BlockInMask) {
  2386. Value *BlockInMaskPart = State.get(BlockInMask, Part);
  2387. Value *ShuffledMask = Builder.CreateShuffleVector(
  2388. BlockInMaskPart,
  2389. createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
  2390. "interleaved.mask");
  2391. GroupMask = MaskForGaps
  2392. ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
  2393. MaskForGaps)
  2394. : ShuffledMask;
  2395. }
  2396. NewLoad =
  2397. Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
  2398. GroupMask, PoisonVec, "wide.masked.vec");
  2399. }
  2400. else
  2401. NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
  2402. Group->getAlign(), "wide.vec");
  2403. Group->addMetadata(NewLoad);
  2404. NewLoads.push_back(NewLoad);
  2405. }
  2406. // For each member in the group, shuffle out the appropriate data from the
  2407. // wide loads.
  2408. unsigned J = 0;
  2409. for (unsigned I = 0; I < InterleaveFactor; ++I) {
  2410. Instruction *Member = Group->getMember(I);
  2411. // Skip the gaps in the group.
  2412. if (!Member)
  2413. continue;
  2414. auto StrideMask =
  2415. createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
  2416. for (unsigned Part = 0; Part < UF; Part++) {
  2417. Value *StridedVec = Builder.CreateShuffleVector(
  2418. NewLoads[Part], StrideMask, "strided.vec");
  2419. // If this member has different type, cast the result type.
  2420. if (Member->getType() != ScalarTy) {
  2421. assert(!VF.isScalable() && "VF is assumed to be non scalable.");
  2422. VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
  2423. StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
  2424. }
  2425. if (Group->isReverse())
  2426. StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
  2427. State.set(VPDefs[J], StridedVec, Part);
  2428. }
  2429. ++J;
  2430. }
  2431. return;
  2432. }
  2433. // The sub vector type for current instruction.
  2434. auto *SubVT = VectorType::get(ScalarTy, VF);
  2435. // Vectorize the interleaved store group.
  2436. MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
  2437. assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
  2438. "masked interleaved groups are not allowed.");
  2439. assert((!MaskForGaps || !VF.isScalable()) &&
  2440. "masking gaps for scalable vectors is not yet supported.");
  2441. for (unsigned Part = 0; Part < UF; Part++) {
  2442. // Collect the stored vector from each member.
  2443. SmallVector<Value *, 4> StoredVecs;
  2444. for (unsigned i = 0; i < InterleaveFactor; i++) {
  2445. assert((Group->getMember(i) || MaskForGaps) &&
  2446. "Fail to get a member from an interleaved store group");
  2447. Instruction *Member = Group->getMember(i);
  2448. // Skip the gaps in the group.
  2449. if (!Member) {
  2450. Value *Undef = PoisonValue::get(SubVT);
  2451. StoredVecs.push_back(Undef);
  2452. continue;
  2453. }
  2454. Value *StoredVec = State.get(StoredValues[i], Part);
  2455. if (Group->isReverse())
  2456. StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
  2457. // If this member has different type, cast it to a unified type.
  2458. if (StoredVec->getType() != SubVT)
  2459. StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
  2460. StoredVecs.push_back(StoredVec);
  2461. }
  2462. // Concatenate all vectors into a wide vector.
  2463. Value *WideVec = concatenateVectors(Builder, StoredVecs);
  2464. // Interleave the elements in the wide vector.
  2465. Value *IVec = Builder.CreateShuffleVector(
  2466. WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
  2467. "interleaved.vec");
  2468. Instruction *NewStoreInstr;
  2469. if (BlockInMask || MaskForGaps) {
  2470. Value *GroupMask = MaskForGaps;
  2471. if (BlockInMask) {
  2472. Value *BlockInMaskPart = State.get(BlockInMask, Part);
  2473. Value *ShuffledMask = Builder.CreateShuffleVector(
  2474. BlockInMaskPart,
  2475. createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
  2476. "interleaved.mask");
  2477. GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
  2478. ShuffledMask, MaskForGaps)
  2479. : ShuffledMask;
  2480. }
  2481. NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
  2482. Group->getAlign(), GroupMask);
  2483. } else
  2484. NewStoreInstr =
  2485. Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
  2486. Group->addMetadata(NewStoreInstr);
  2487. }
  2488. }
  2489. void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
  2490. VPReplicateRecipe *RepRecipe,
  2491. const VPIteration &Instance,
  2492. bool IfPredicateInstr,
  2493. VPTransformState &State) {
  2494. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  2495. // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
  2496. // the first lane and part.
  2497. if (isa<NoAliasScopeDeclInst>(Instr))
  2498. if (!Instance.isFirstIteration())
  2499. return;
  2500. setDebugLocFromInst(Instr);
  2501. // Does this instruction return a value ?
  2502. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  2503. Instruction *Cloned = Instr->clone();
  2504. if (!IsVoidRetTy)
  2505. Cloned->setName(Instr->getName() + ".cloned");
  2506. // If the scalarized instruction contributes to the address computation of a
  2507. // widen masked load/store which was in a basic block that needed predication
  2508. // and is not predicated after vectorization, we can't propagate
  2509. // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
  2510. // instruction could feed a poison value to the base address of the widen
  2511. // load/store.
  2512. if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
  2513. Cloned->dropPoisonGeneratingFlags();
  2514. State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
  2515. Builder.GetInsertPoint());
  2516. // Replace the operands of the cloned instructions with their scalar
  2517. // equivalents in the new loop.
  2518. for (auto &I : enumerate(RepRecipe->operands())) {
  2519. auto InputInstance = Instance;
  2520. VPValue *Operand = I.value();
  2521. if (State.Plan->isUniformAfterVectorization(Operand))
  2522. InputInstance.Lane = VPLane::getFirstLane();
  2523. Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
  2524. }
  2525. addNewMetadata(Cloned, Instr);
  2526. // Place the cloned scalar in the new loop.
  2527. Builder.Insert(Cloned);
  2528. State.set(RepRecipe, Cloned, Instance);
  2529. // If we just cloned a new assumption, add it the assumption cache.
  2530. if (auto *II = dyn_cast<AssumeInst>(Cloned))
  2531. AC->registerAssumption(II);
  2532. // End if-block.
  2533. if (IfPredicateInstr)
  2534. PredicatedInstructions.push_back(Cloned);
  2535. }
  2536. void InnerLoopVectorizer::createHeaderBranch(Loop *L) {
  2537. BasicBlock *Header = L->getHeader();
  2538. assert(!L->getLoopLatch() && "loop should not have a latch at this point");
  2539. IRBuilder<> B(Header->getTerminator());
  2540. Instruction *OldInst =
  2541. getDebugLocFromInstOrOperands(Legal->getPrimaryInduction());
  2542. setDebugLocFromInst(OldInst, &B);
  2543. // Connect the header to the exit and header blocks and replace the old
  2544. // terminator.
  2545. B.CreateCondBr(B.getTrue(), L->getUniqueExitBlock(), Header);
  2546. // Now we have two terminators. Remove the old one from the block.
  2547. Header->getTerminator()->eraseFromParent();
  2548. }
  2549. Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
  2550. if (TripCount)
  2551. return TripCount;
  2552. assert(L && "Create Trip Count for null loop.");
  2553. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2554. // Find the loop boundaries.
  2555. ScalarEvolution *SE = PSE.getSE();
  2556. const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
  2557. assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
  2558. "Invalid loop count");
  2559. Type *IdxTy = Legal->getWidestInductionType();
  2560. assert(IdxTy && "No type for induction");
  2561. // The exit count might have the type of i64 while the phi is i32. This can
  2562. // happen if we have an induction variable that is sign extended before the
  2563. // compare. The only way that we get a backedge taken count is that the
  2564. // induction variable was signed and as such will not overflow. In such a case
  2565. // truncation is legal.
  2566. if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
  2567. IdxTy->getPrimitiveSizeInBits())
  2568. BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
  2569. BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
  2570. // Get the total trip count from the count by adding 1.
  2571. const SCEV *ExitCount = SE->getAddExpr(
  2572. BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
  2573. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  2574. // Expand the trip count and place the new instructions in the preheader.
  2575. // Notice that the pre-header does not change, only the loop body.
  2576. SCEVExpander Exp(*SE, DL, "induction");
  2577. // Count holds the overall loop count (N).
  2578. TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
  2579. L->getLoopPreheader()->getTerminator());
  2580. if (TripCount->getType()->isPointerTy())
  2581. TripCount =
  2582. CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
  2583. L->getLoopPreheader()->getTerminator());
  2584. return TripCount;
  2585. }
  2586. Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
  2587. if (VectorTripCount)
  2588. return VectorTripCount;
  2589. Value *TC = getOrCreateTripCount(L);
  2590. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2591. Type *Ty = TC->getType();
  2592. // This is where we can make the step a runtime constant.
  2593. Value *Step = createStepForVF(Builder, Ty, VF, UF);
  2594. // If the tail is to be folded by masking, round the number of iterations N
  2595. // up to a multiple of Step instead of rounding down. This is done by first
  2596. // adding Step-1 and then rounding down. Note that it's ok if this addition
  2597. // overflows: the vector induction variable will eventually wrap to zero given
  2598. // that it starts at zero and its Step is a power of two; the loop will then
  2599. // exit, with the last early-exit vector comparison also producing all-true.
  2600. if (Cost->foldTailByMasking()) {
  2601. assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
  2602. "VF*UF must be a power of 2 when folding tail by masking");
  2603. Value *NumLanes = getRuntimeVF(Builder, Ty, VF * UF);
  2604. TC = Builder.CreateAdd(
  2605. TC, Builder.CreateSub(NumLanes, ConstantInt::get(Ty, 1)), "n.rnd.up");
  2606. }
  2607. // Now we need to generate the expression for the part of the loop that the
  2608. // vectorized body will execute. This is equal to N - (N % Step) if scalar
  2609. // iterations are not required for correctness, or N - Step, otherwise. Step
  2610. // is equal to the vectorization factor (number of SIMD elements) times the
  2611. // unroll factor (number of SIMD instructions).
  2612. Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
  2613. // There are cases where we *must* run at least one iteration in the remainder
  2614. // loop. See the cost model for when this can happen. If the step evenly
  2615. // divides the trip count, we set the remainder to be equal to the step. If
  2616. // the step does not evenly divide the trip count, no adjustment is necessary
  2617. // since there will already be scalar iterations. Note that the minimum
  2618. // iterations check ensures that N >= Step.
  2619. if (Cost->requiresScalarEpilogue(VF)) {
  2620. auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
  2621. R = Builder.CreateSelect(IsZero, Step, R);
  2622. }
  2623. VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
  2624. return VectorTripCount;
  2625. }
  2626. Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
  2627. const DataLayout &DL) {
  2628. // Verify that V is a vector type with same number of elements as DstVTy.
  2629. auto *DstFVTy = cast<FixedVectorType>(DstVTy);
  2630. unsigned VF = DstFVTy->getNumElements();
  2631. auto *SrcVecTy = cast<FixedVectorType>(V->getType());
  2632. assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
  2633. Type *SrcElemTy = SrcVecTy->getElementType();
  2634. Type *DstElemTy = DstFVTy->getElementType();
  2635. assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
  2636. "Vector elements must have same size");
  2637. // Do a direct cast if element types are castable.
  2638. if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
  2639. return Builder.CreateBitOrPointerCast(V, DstFVTy);
  2640. }
  2641. // V cannot be directly casted to desired vector type.
  2642. // May happen when V is a floating point vector but DstVTy is a vector of
  2643. // pointers or vice-versa. Handle this using a two-step bitcast using an
  2644. // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
  2645. assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
  2646. "Only one type should be a pointer type");
  2647. assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
  2648. "Only one type should be a floating point type");
  2649. Type *IntTy =
  2650. IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
  2651. auto *VecIntTy = FixedVectorType::get(IntTy, VF);
  2652. Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
  2653. return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
  2654. }
  2655. void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
  2656. BasicBlock *Bypass) {
  2657. Value *Count = getOrCreateTripCount(L);
  2658. // Reuse existing vector loop preheader for TC checks.
  2659. // Note that new preheader block is generated for vector loop.
  2660. BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
  2661. IRBuilder<> Builder(TCCheckBlock->getTerminator());
  2662. // Generate code to check if the loop's trip count is less than VF * UF, or
  2663. // equal to it in case a scalar epilogue is required; this implies that the
  2664. // vector trip count is zero. This check also covers the case where adding one
  2665. // to the backedge-taken count overflowed leading to an incorrect trip count
  2666. // of zero. In this case we will also jump to the scalar loop.
  2667. auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
  2668. : ICmpInst::ICMP_ULT;
  2669. // If tail is to be folded, vector loop takes care of all iterations.
  2670. Value *CheckMinIters = Builder.getFalse();
  2671. if (!Cost->foldTailByMasking()) {
  2672. Value *Step = createStepForVF(Builder, Count->getType(), VF, UF);
  2673. CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
  2674. }
  2675. // Create new preheader for vector loop.
  2676. LoopVectorPreHeader =
  2677. SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
  2678. "vector.ph");
  2679. assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
  2680. DT->getNode(Bypass)->getIDom()) &&
  2681. "TC check is expected to dominate Bypass");
  2682. // Update dominator for Bypass & LoopExit (if needed).
  2683. DT->changeImmediateDominator(Bypass, TCCheckBlock);
  2684. if (!Cost->requiresScalarEpilogue(VF))
  2685. // If there is an epilogue which must run, there's no edge from the
  2686. // middle block to exit blocks and thus no need to update the immediate
  2687. // dominator of the exit blocks.
  2688. DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
  2689. ReplaceInstWithInst(
  2690. TCCheckBlock->getTerminator(),
  2691. BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
  2692. LoopBypassBlocks.push_back(TCCheckBlock);
  2693. }
  2694. BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
  2695. BasicBlock *const SCEVCheckBlock =
  2696. RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
  2697. if (!SCEVCheckBlock)
  2698. return nullptr;
  2699. assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
  2700. (OptForSizeBasedOnProfile &&
  2701. Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
  2702. "Cannot SCEV check stride or overflow when optimizing for size");
  2703. // Update dominator only if this is first RT check.
  2704. if (LoopBypassBlocks.empty()) {
  2705. DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
  2706. if (!Cost->requiresScalarEpilogue(VF))
  2707. // If there is an epilogue which must run, there's no edge from the
  2708. // middle block to exit blocks and thus no need to update the immediate
  2709. // dominator of the exit blocks.
  2710. DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
  2711. }
  2712. LoopBypassBlocks.push_back(SCEVCheckBlock);
  2713. AddedSafetyChecks = true;
  2714. return SCEVCheckBlock;
  2715. }
  2716. BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
  2717. BasicBlock *Bypass) {
  2718. // VPlan-native path does not do any analysis for runtime checks currently.
  2719. if (EnableVPlanNativePath)
  2720. return nullptr;
  2721. BasicBlock *const MemCheckBlock =
  2722. RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
  2723. // Check if we generated code that checks in runtime if arrays overlap. We put
  2724. // the checks into a separate block to make the more common case of few
  2725. // elements faster.
  2726. if (!MemCheckBlock)
  2727. return nullptr;
  2728. if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
  2729. assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
  2730. "Cannot emit memory checks when optimizing for size, unless forced "
  2731. "to vectorize.");
  2732. ORE->emit([&]() {
  2733. return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
  2734. L->getStartLoc(), L->getHeader())
  2735. << "Code-size may be reduced by not forcing "
  2736. "vectorization, or by source-code modifications "
  2737. "eliminating the need for runtime checks "
  2738. "(e.g., adding 'restrict').";
  2739. });
  2740. }
  2741. LoopBypassBlocks.push_back(MemCheckBlock);
  2742. AddedSafetyChecks = true;
  2743. // We currently don't use LoopVersioning for the actual loop cloning but we
  2744. // still use it to add the noalias metadata.
  2745. LVer = std::make_unique<LoopVersioning>(
  2746. *Legal->getLAI(),
  2747. Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
  2748. DT, PSE.getSE());
  2749. LVer->prepareNoAliasMetadata();
  2750. return MemCheckBlock;
  2751. }
  2752. Value *InnerLoopVectorizer::emitTransformedIndex(
  2753. IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
  2754. const InductionDescriptor &ID, BasicBlock *VectorHeader) const {
  2755. SCEVExpander Exp(*SE, DL, "induction");
  2756. auto Step = ID.getStep();
  2757. auto StartValue = ID.getStartValue();
  2758. assert(Index->getType()->getScalarType() == Step->getType() &&
  2759. "Index scalar type does not match StepValue type");
  2760. // Note: the IR at this point is broken. We cannot use SE to create any new
  2761. // SCEV and then expand it, hoping that SCEV's simplification will give us
  2762. // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
  2763. // lead to various SCEV crashes. So all we can do is to use builder and rely
  2764. // on InstCombine for future simplifications. Here we handle some trivial
  2765. // cases only.
  2766. auto CreateAdd = [&B](Value *X, Value *Y) {
  2767. assert(X->getType() == Y->getType() && "Types don't match!");
  2768. if (auto *CX = dyn_cast<ConstantInt>(X))
  2769. if (CX->isZero())
  2770. return Y;
  2771. if (auto *CY = dyn_cast<ConstantInt>(Y))
  2772. if (CY->isZero())
  2773. return X;
  2774. return B.CreateAdd(X, Y);
  2775. };
  2776. // We allow X to be a vector type, in which case Y will potentially be
  2777. // splatted into a vector with the same element count.
  2778. auto CreateMul = [&B](Value *X, Value *Y) {
  2779. assert(X->getType()->getScalarType() == Y->getType() &&
  2780. "Types don't match!");
  2781. if (auto *CX = dyn_cast<ConstantInt>(X))
  2782. if (CX->isOne())
  2783. return Y;
  2784. if (auto *CY = dyn_cast<ConstantInt>(Y))
  2785. if (CY->isOne())
  2786. return X;
  2787. VectorType *XVTy = dyn_cast<VectorType>(X->getType());
  2788. if (XVTy && !isa<VectorType>(Y->getType()))
  2789. Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
  2790. return B.CreateMul(X, Y);
  2791. };
  2792. // Get a suitable insert point for SCEV expansion. For blocks in the vector
  2793. // loop, choose the end of the vector loop header (=VectorHeader), because
  2794. // the DomTree is not kept up-to-date for additional blocks generated in the
  2795. // vector loop. By using the header as insertion point, we guarantee that the
  2796. // expanded instructions dominate all their uses.
  2797. auto GetInsertPoint = [this, &B, VectorHeader]() {
  2798. BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
  2799. if (InsertBB != LoopVectorBody &&
  2800. LI->getLoopFor(VectorHeader) == LI->getLoopFor(InsertBB))
  2801. return VectorHeader->getTerminator();
  2802. return &*B.GetInsertPoint();
  2803. };
  2804. switch (ID.getKind()) {
  2805. case InductionDescriptor::IK_IntInduction: {
  2806. assert(!isa<VectorType>(Index->getType()) &&
  2807. "Vector indices not supported for integer inductions yet");
  2808. assert(Index->getType() == StartValue->getType() &&
  2809. "Index type does not match StartValue type");
  2810. if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
  2811. return B.CreateSub(StartValue, Index);
  2812. auto *Offset = CreateMul(
  2813. Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
  2814. return CreateAdd(StartValue, Offset);
  2815. }
  2816. case InductionDescriptor::IK_PtrInduction: {
  2817. assert(isa<SCEVConstant>(Step) &&
  2818. "Expected constant step for pointer induction");
  2819. return B.CreateGEP(
  2820. ID.getElementType(), StartValue,
  2821. CreateMul(Index,
  2822. Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
  2823. GetInsertPoint())));
  2824. }
  2825. case InductionDescriptor::IK_FpInduction: {
  2826. assert(!isa<VectorType>(Index->getType()) &&
  2827. "Vector indices not supported for FP inductions yet");
  2828. assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
  2829. auto InductionBinOp = ID.getInductionBinOp();
  2830. assert(InductionBinOp &&
  2831. (InductionBinOp->getOpcode() == Instruction::FAdd ||
  2832. InductionBinOp->getOpcode() == Instruction::FSub) &&
  2833. "Original bin op should be defined for FP induction");
  2834. Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
  2835. Value *MulExp = B.CreateFMul(StepValue, Index);
  2836. return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
  2837. "induction");
  2838. }
  2839. case InductionDescriptor::IK_NoInduction:
  2840. return nullptr;
  2841. }
  2842. llvm_unreachable("invalid enum");
  2843. }
  2844. Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
  2845. LoopScalarBody = OrigLoop->getHeader();
  2846. LoopVectorPreHeader = OrigLoop->getLoopPreheader();
  2847. assert(LoopVectorPreHeader && "Invalid loop structure");
  2848. LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
  2849. assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
  2850. "multiple exit loop without required epilogue?");
  2851. LoopMiddleBlock =
  2852. SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
  2853. LI, nullptr, Twine(Prefix) + "middle.block");
  2854. LoopScalarPreHeader =
  2855. SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
  2856. nullptr, Twine(Prefix) + "scalar.ph");
  2857. auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
  2858. // Set up the middle block terminator. Two cases:
  2859. // 1) If we know that we must execute the scalar epilogue, emit an
  2860. // unconditional branch.
  2861. // 2) Otherwise, we must have a single unique exit block (due to how we
  2862. // implement the multiple exit case). In this case, set up a conditonal
  2863. // branch from the middle block to the loop scalar preheader, and the
  2864. // exit block. completeLoopSkeleton will update the condition to use an
  2865. // iteration check, if required to decide whether to execute the remainder.
  2866. BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
  2867. BranchInst::Create(LoopScalarPreHeader) :
  2868. BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
  2869. Builder.getTrue());
  2870. BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
  2871. ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
  2872. // We intentionally don't let SplitBlock to update LoopInfo since
  2873. // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
  2874. // LoopVectorBody is explicitly added to the correct place few lines later.
  2875. LoopVectorBody =
  2876. SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
  2877. nullptr, nullptr, Twine(Prefix) + "vector.body");
  2878. // Update dominator for loop exit.
  2879. if (!Cost->requiresScalarEpilogue(VF))
  2880. // If there is an epilogue which must run, there's no edge from the
  2881. // middle block to exit blocks and thus no need to update the immediate
  2882. // dominator of the exit blocks.
  2883. DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
  2884. // Create and register the new vector loop.
  2885. Loop *Lp = LI->AllocateLoop();
  2886. Loop *ParentLoop = OrigLoop->getParentLoop();
  2887. // Insert the new loop into the loop nest and register the new basic blocks
  2888. // before calling any utilities such as SCEV that require valid LoopInfo.
  2889. if (ParentLoop) {
  2890. ParentLoop->addChildLoop(Lp);
  2891. } else {
  2892. LI->addTopLevelLoop(Lp);
  2893. }
  2894. Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
  2895. return Lp;
  2896. }
  2897. void InnerLoopVectorizer::createInductionResumeValues(
  2898. Loop *L, std::pair<BasicBlock *, Value *> AdditionalBypass) {
  2899. assert(((AdditionalBypass.first && AdditionalBypass.second) ||
  2900. (!AdditionalBypass.first && !AdditionalBypass.second)) &&
  2901. "Inconsistent information about additional bypass.");
  2902. Value *VectorTripCount = getOrCreateVectorTripCount(L);
  2903. assert(VectorTripCount && L && "Expected valid arguments");
  2904. // We are going to resume the execution of the scalar loop.
  2905. // Go over all of the induction variables that we found and fix the
  2906. // PHIs that are left in the scalar version of the loop.
  2907. // The starting values of PHI nodes depend on the counter of the last
  2908. // iteration in the vectorized loop.
  2909. // If we come from a bypass edge then we need to start from the original
  2910. // start value.
  2911. Instruction *OldInduction = Legal->getPrimaryInduction();
  2912. for (auto &InductionEntry : Legal->getInductionVars()) {
  2913. PHINode *OrigPhi = InductionEntry.first;
  2914. InductionDescriptor II = InductionEntry.second;
  2915. // Create phi nodes to merge from the backedge-taken check block.
  2916. PHINode *BCResumeVal =
  2917. PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
  2918. LoopScalarPreHeader->getTerminator());
  2919. // Copy original phi DL over to the new one.
  2920. BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
  2921. Value *&EndValue = IVEndValues[OrigPhi];
  2922. Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
  2923. if (OrigPhi == OldInduction) {
  2924. // We know what the end value is.
  2925. EndValue = VectorTripCount;
  2926. } else {
  2927. IRBuilder<> B(L->getLoopPreheader()->getTerminator());
  2928. // Fast-math-flags propagate from the original induction instruction.
  2929. if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
  2930. B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
  2931. Type *StepType = II.getStep()->getType();
  2932. Instruction::CastOps CastOp =
  2933. CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
  2934. Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
  2935. const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
  2936. EndValue =
  2937. emitTransformedIndex(B, CRD, PSE.getSE(), DL, II, LoopVectorBody);
  2938. EndValue->setName("ind.end");
  2939. // Compute the end value for the additional bypass (if applicable).
  2940. if (AdditionalBypass.first) {
  2941. B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
  2942. CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
  2943. StepType, true);
  2944. CRD =
  2945. B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
  2946. EndValueFromAdditionalBypass =
  2947. emitTransformedIndex(B, CRD, PSE.getSE(), DL, II, LoopVectorBody);
  2948. EndValueFromAdditionalBypass->setName("ind.end");
  2949. }
  2950. }
  2951. // The new PHI merges the original incoming value, in case of a bypass,
  2952. // or the value at the end of the vectorized loop.
  2953. BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
  2954. // Fix the scalar body counter (PHI node).
  2955. // The old induction's phi node in the scalar body needs the truncated
  2956. // value.
  2957. for (BasicBlock *BB : LoopBypassBlocks)
  2958. BCResumeVal->addIncoming(II.getStartValue(), BB);
  2959. if (AdditionalBypass.first)
  2960. BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
  2961. EndValueFromAdditionalBypass);
  2962. OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
  2963. }
  2964. }
  2965. BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
  2966. MDNode *OrigLoopID) {
  2967. assert(L && "Expected valid loop.");
  2968. // The trip counts should be cached by now.
  2969. Value *Count = getOrCreateTripCount(L);
  2970. Value *VectorTripCount = getOrCreateVectorTripCount(L);
  2971. auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
  2972. // Add a check in the middle block to see if we have completed
  2973. // all of the iterations in the first vector loop. Three cases:
  2974. // 1) If we require a scalar epilogue, there is no conditional branch as
  2975. // we unconditionally branch to the scalar preheader. Do nothing.
  2976. // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
  2977. // Thus if tail is to be folded, we know we don't need to run the
  2978. // remainder and we can use the previous value for the condition (true).
  2979. // 3) Otherwise, construct a runtime check.
  2980. if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
  2981. Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
  2982. Count, VectorTripCount, "cmp.n",
  2983. LoopMiddleBlock->getTerminator());
  2984. // Here we use the same DebugLoc as the scalar loop latch terminator instead
  2985. // of the corresponding compare because they may have ended up with
  2986. // different line numbers and we want to avoid awkward line stepping while
  2987. // debugging. Eg. if the compare has got a line number inside the loop.
  2988. CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
  2989. cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
  2990. }
  2991. // Get ready to start creating new instructions into the vectorized body.
  2992. assert(LoopVectorPreHeader == L->getLoopPreheader() &&
  2993. "Inconsistent vector loop preheader");
  2994. Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
  2995. #ifdef EXPENSIVE_CHECKS
  2996. assert(DT->verify(DominatorTree::VerificationLevel::Fast));
  2997. LI->verify(*DT);
  2998. #endif
  2999. return LoopVectorPreHeader;
  3000. }
  3001. std::pair<BasicBlock *, Value *>
  3002. InnerLoopVectorizer::createVectorizedLoopSkeleton() {
  3003. /*
  3004. In this function we generate a new loop. The new loop will contain
  3005. the vectorized instructions while the old loop will continue to run the
  3006. scalar remainder.
  3007. [ ] <-- loop iteration number check.
  3008. / |
  3009. / v
  3010. | [ ] <-- vector loop bypass (may consist of multiple blocks).
  3011. | / |
  3012. | / v
  3013. || [ ] <-- vector pre header.
  3014. |/ |
  3015. | v
  3016. | [ ] \
  3017. | [ ]_| <-- vector loop.
  3018. | |
  3019. | v
  3020. \ -[ ] <--- middle-block.
  3021. \/ |
  3022. /\ v
  3023. | ->[ ] <--- new preheader.
  3024. | |
  3025. (opt) v <-- edge from middle to exit iff epilogue is not required.
  3026. | [ ] \
  3027. | [ ]_| <-- old scalar loop to handle remainder (scalar epilogue).
  3028. \ |
  3029. \ v
  3030. >[ ] <-- exit block(s).
  3031. ...
  3032. */
  3033. // Get the metadata of the original loop before it gets modified.
  3034. MDNode *OrigLoopID = OrigLoop->getLoopID();
  3035. // Workaround! Compute the trip count of the original loop and cache it
  3036. // before we start modifying the CFG. This code has a systemic problem
  3037. // wherein it tries to run analysis over partially constructed IR; this is
  3038. // wrong, and not simply for SCEV. The trip count of the original loop
  3039. // simply happens to be prone to hitting this in practice. In theory, we
  3040. // can hit the same issue for any SCEV, or ValueTracking query done during
  3041. // mutation. See PR49900.
  3042. getOrCreateTripCount(OrigLoop);
  3043. // Create an empty vector loop, and prepare basic blocks for the runtime
  3044. // checks.
  3045. Loop *Lp = createVectorLoopSkeleton("");
  3046. // Now, compare the new count to zero. If it is zero skip the vector loop and
  3047. // jump to the scalar loop. This check also covers the case where the
  3048. // backedge-taken count is uint##_max: adding one to it will overflow leading
  3049. // to an incorrect trip count of zero. In this (rare) case we will also jump
  3050. // to the scalar loop.
  3051. emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
  3052. // Generate the code to check any assumptions that we've made for SCEV
  3053. // expressions.
  3054. emitSCEVChecks(Lp, LoopScalarPreHeader);
  3055. // Generate the code that checks in runtime if arrays overlap. We put the
  3056. // checks into a separate block to make the more common case of few elements
  3057. // faster.
  3058. emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
  3059. createHeaderBranch(Lp);
  3060. // Emit phis for the new starting index of the scalar loop.
  3061. createInductionResumeValues(Lp);
  3062. return {completeLoopSkeleton(Lp, OrigLoopID), nullptr};
  3063. }
  3064. // Fix up external users of the induction variable. At this point, we are
  3065. // in LCSSA form, with all external PHIs that use the IV having one input value,
  3066. // coming from the remainder loop. We need those PHIs to also have a correct
  3067. // value for the IV when arriving directly from the middle block.
  3068. void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
  3069. const InductionDescriptor &II,
  3070. Value *CountRoundDown, Value *EndValue,
  3071. BasicBlock *MiddleBlock) {
  3072. // There are two kinds of external IV usages - those that use the value
  3073. // computed in the last iteration (the PHI) and those that use the penultimate
  3074. // value (the value that feeds into the phi from the loop latch).
  3075. // We allow both, but they, obviously, have different values.
  3076. assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
  3077. DenseMap<Value *, Value *> MissingVals;
  3078. // An external user of the last iteration's value should see the value that
  3079. // the remainder loop uses to initialize its own IV.
  3080. Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
  3081. for (User *U : PostInc->users()) {
  3082. Instruction *UI = cast<Instruction>(U);
  3083. if (!OrigLoop->contains(UI)) {
  3084. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  3085. MissingVals[UI] = EndValue;
  3086. }
  3087. }
  3088. // An external user of the penultimate value need to see EndValue - Step.
  3089. // The simplest way to get this is to recompute it from the constituent SCEVs,
  3090. // that is Start + (Step * (CRD - 1)).
  3091. for (User *U : OrigPhi->users()) {
  3092. auto *UI = cast<Instruction>(U);
  3093. if (!OrigLoop->contains(UI)) {
  3094. const DataLayout &DL =
  3095. OrigLoop->getHeader()->getModule()->getDataLayout();
  3096. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  3097. IRBuilder<> B(MiddleBlock->getTerminator());
  3098. // Fast-math-flags propagate from the original induction instruction.
  3099. if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
  3100. B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
  3101. Value *CountMinusOne = B.CreateSub(
  3102. CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
  3103. Value *CMO =
  3104. !II.getStep()->getType()->isIntegerTy()
  3105. ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
  3106. II.getStep()->getType())
  3107. : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
  3108. CMO->setName("cast.cmo");
  3109. Value *Escape =
  3110. emitTransformedIndex(B, CMO, PSE.getSE(), DL, II, LoopVectorBody);
  3111. Escape->setName("ind.escape");
  3112. MissingVals[UI] = Escape;
  3113. }
  3114. }
  3115. for (auto &I : MissingVals) {
  3116. PHINode *PHI = cast<PHINode>(I.first);
  3117. // One corner case we have to handle is two IVs "chasing" each-other,
  3118. // that is %IV2 = phi [...], [ %IV1, %latch ]
  3119. // In this case, if IV1 has an external use, we need to avoid adding both
  3120. // "last value of IV1" and "penultimate value of IV2". So, verify that we
  3121. // don't already have an incoming value for the middle block.
  3122. if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
  3123. PHI->addIncoming(I.second, MiddleBlock);
  3124. }
  3125. }
  3126. namespace {
  3127. struct CSEDenseMapInfo {
  3128. static bool canHandle(const Instruction *I) {
  3129. return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
  3130. isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
  3131. }
  3132. static inline Instruction *getEmptyKey() {
  3133. return DenseMapInfo<Instruction *>::getEmptyKey();
  3134. }
  3135. static inline Instruction *getTombstoneKey() {
  3136. return DenseMapInfo<Instruction *>::getTombstoneKey();
  3137. }
  3138. static unsigned getHashValue(const Instruction *I) {
  3139. assert(canHandle(I) && "Unknown instruction!");
  3140. return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
  3141. I->value_op_end()));
  3142. }
  3143. static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
  3144. if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
  3145. LHS == getTombstoneKey() || RHS == getTombstoneKey())
  3146. return LHS == RHS;
  3147. return LHS->isIdenticalTo(RHS);
  3148. }
  3149. };
  3150. } // end anonymous namespace
  3151. ///Perform cse of induction variable instructions.
  3152. static void cse(BasicBlock *BB) {
  3153. // Perform simple cse.
  3154. SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
  3155. for (Instruction &In : llvm::make_early_inc_range(*BB)) {
  3156. if (!CSEDenseMapInfo::canHandle(&In))
  3157. continue;
  3158. // Check if we can replace this instruction with any of the
  3159. // visited instructions.
  3160. if (Instruction *V = CSEMap.lookup(&In)) {
  3161. In.replaceAllUsesWith(V);
  3162. In.eraseFromParent();
  3163. continue;
  3164. }
  3165. CSEMap[&In] = &In;
  3166. }
  3167. }
  3168. InstructionCost
  3169. LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
  3170. bool &NeedToScalarize) const {
  3171. Function *F = CI->getCalledFunction();
  3172. Type *ScalarRetTy = CI->getType();
  3173. SmallVector<Type *, 4> Tys, ScalarTys;
  3174. for (auto &ArgOp : CI->args())
  3175. ScalarTys.push_back(ArgOp->getType());
  3176. // Estimate cost of scalarized vector call. The source operands are assumed
  3177. // to be vectors, so we need to extract individual elements from there,
  3178. // execute VF scalar calls, and then gather the result into the vector return
  3179. // value.
  3180. InstructionCost ScalarCallCost =
  3181. TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
  3182. if (VF.isScalar())
  3183. return ScalarCallCost;
  3184. // Compute corresponding vector type for return value and arguments.
  3185. Type *RetTy = ToVectorTy(ScalarRetTy, VF);
  3186. for (Type *ScalarTy : ScalarTys)
  3187. Tys.push_back(ToVectorTy(ScalarTy, VF));
  3188. // Compute costs of unpacking argument values for the scalar calls and
  3189. // packing the return values to a vector.
  3190. InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
  3191. InstructionCost Cost =
  3192. ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
  3193. // If we can't emit a vector call for this function, then the currently found
  3194. // cost is the cost we need to return.
  3195. NeedToScalarize = true;
  3196. VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
  3197. Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
  3198. if (!TLI || CI->isNoBuiltin() || !VecFunc)
  3199. return Cost;
  3200. // If the corresponding vector cost is cheaper, return its cost.
  3201. InstructionCost VectorCallCost =
  3202. TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
  3203. if (VectorCallCost < Cost) {
  3204. NeedToScalarize = false;
  3205. Cost = VectorCallCost;
  3206. }
  3207. return Cost;
  3208. }
  3209. static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
  3210. if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
  3211. return Elt;
  3212. return VectorType::get(Elt, VF);
  3213. }
  3214. InstructionCost
  3215. LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
  3216. ElementCount VF) const {
  3217. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  3218. assert(ID && "Expected intrinsic call!");
  3219. Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
  3220. FastMathFlags FMF;
  3221. if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
  3222. FMF = FPMO->getFastMathFlags();
  3223. SmallVector<const Value *> Arguments(CI->args());
  3224. FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
  3225. SmallVector<Type *> ParamTys;
  3226. std::transform(FTy->param_begin(), FTy->param_end(),
  3227. std::back_inserter(ParamTys),
  3228. [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
  3229. IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
  3230. dyn_cast<IntrinsicInst>(CI));
  3231. return TTI.getIntrinsicInstrCost(CostAttrs,
  3232. TargetTransformInfo::TCK_RecipThroughput);
  3233. }
  3234. static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
  3235. auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
  3236. auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
  3237. return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
  3238. }
  3239. static Type *largestIntegerVectorType(Type *T1, Type *T2) {
  3240. auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
  3241. auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
  3242. return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
  3243. }
  3244. void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
  3245. // For every instruction `I` in MinBWs, truncate the operands, create a
  3246. // truncated version of `I` and reextend its result. InstCombine runs
  3247. // later and will remove any ext/trunc pairs.
  3248. SmallPtrSet<Value *, 4> Erased;
  3249. for (const auto &KV : Cost->getMinimalBitwidths()) {
  3250. // If the value wasn't vectorized, we must maintain the original scalar
  3251. // type. The absence of the value from State indicates that it
  3252. // wasn't vectorized.
  3253. // FIXME: Should not rely on getVPValue at this point.
  3254. VPValue *Def = State.Plan->getVPValue(KV.first, true);
  3255. if (!State.hasAnyVectorValue(Def))
  3256. continue;
  3257. for (unsigned Part = 0; Part < UF; ++Part) {
  3258. Value *I = State.get(Def, Part);
  3259. if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
  3260. continue;
  3261. Type *OriginalTy = I->getType();
  3262. Type *ScalarTruncatedTy =
  3263. IntegerType::get(OriginalTy->getContext(), KV.second);
  3264. auto *TruncatedTy = VectorType::get(
  3265. ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
  3266. if (TruncatedTy == OriginalTy)
  3267. continue;
  3268. IRBuilder<> B(cast<Instruction>(I));
  3269. auto ShrinkOperand = [&](Value *V) -> Value * {
  3270. if (auto *ZI = dyn_cast<ZExtInst>(V))
  3271. if (ZI->getSrcTy() == TruncatedTy)
  3272. return ZI->getOperand(0);
  3273. return B.CreateZExtOrTrunc(V, TruncatedTy);
  3274. };
  3275. // The actual instruction modification depends on the instruction type,
  3276. // unfortunately.
  3277. Value *NewI = nullptr;
  3278. if (auto *BO = dyn_cast<BinaryOperator>(I)) {
  3279. NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
  3280. ShrinkOperand(BO->getOperand(1)));
  3281. // Any wrapping introduced by shrinking this operation shouldn't be
  3282. // considered undefined behavior. So, we can't unconditionally copy
  3283. // arithmetic wrapping flags to NewI.
  3284. cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
  3285. } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
  3286. NewI =
  3287. B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
  3288. ShrinkOperand(CI->getOperand(1)));
  3289. } else if (auto *SI = dyn_cast<SelectInst>(I)) {
  3290. NewI = B.CreateSelect(SI->getCondition(),
  3291. ShrinkOperand(SI->getTrueValue()),
  3292. ShrinkOperand(SI->getFalseValue()));
  3293. } else if (auto *CI = dyn_cast<CastInst>(I)) {
  3294. switch (CI->getOpcode()) {
  3295. default:
  3296. llvm_unreachable("Unhandled cast!");
  3297. case Instruction::Trunc:
  3298. NewI = ShrinkOperand(CI->getOperand(0));
  3299. break;
  3300. case Instruction::SExt:
  3301. NewI = B.CreateSExtOrTrunc(
  3302. CI->getOperand(0),
  3303. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  3304. break;
  3305. case Instruction::ZExt:
  3306. NewI = B.CreateZExtOrTrunc(
  3307. CI->getOperand(0),
  3308. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  3309. break;
  3310. }
  3311. } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
  3312. auto Elements0 =
  3313. cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
  3314. auto *O0 = B.CreateZExtOrTrunc(
  3315. SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
  3316. auto Elements1 =
  3317. cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
  3318. auto *O1 = B.CreateZExtOrTrunc(
  3319. SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
  3320. NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
  3321. } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
  3322. // Don't do anything with the operands, just extend the result.
  3323. continue;
  3324. } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
  3325. auto Elements =
  3326. cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
  3327. auto *O0 = B.CreateZExtOrTrunc(
  3328. IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  3329. auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
  3330. NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
  3331. } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
  3332. auto Elements =
  3333. cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
  3334. auto *O0 = B.CreateZExtOrTrunc(
  3335. EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  3336. NewI = B.CreateExtractElement(O0, EE->getOperand(2));
  3337. } else {
  3338. // If we don't know what to do, be conservative and don't do anything.
  3339. continue;
  3340. }
  3341. // Lastly, extend the result.
  3342. NewI->takeName(cast<Instruction>(I));
  3343. Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
  3344. I->replaceAllUsesWith(Res);
  3345. cast<Instruction>(I)->eraseFromParent();
  3346. Erased.insert(I);
  3347. State.reset(Def, Res, Part);
  3348. }
  3349. }
  3350. // We'll have created a bunch of ZExts that are now parentless. Clean up.
  3351. for (const auto &KV : Cost->getMinimalBitwidths()) {
  3352. // If the value wasn't vectorized, we must maintain the original scalar
  3353. // type. The absence of the value from State indicates that it
  3354. // wasn't vectorized.
  3355. // FIXME: Should not rely on getVPValue at this point.
  3356. VPValue *Def = State.Plan->getVPValue(KV.first, true);
  3357. if (!State.hasAnyVectorValue(Def))
  3358. continue;
  3359. for (unsigned Part = 0; Part < UF; ++Part) {
  3360. Value *I = State.get(Def, Part);
  3361. ZExtInst *Inst = dyn_cast<ZExtInst>(I);
  3362. if (Inst && Inst->use_empty()) {
  3363. Value *NewI = Inst->getOperand(0);
  3364. Inst->eraseFromParent();
  3365. State.reset(Def, NewI, Part);
  3366. }
  3367. }
  3368. }
  3369. }
  3370. void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
  3371. // Insert truncates and extends for any truncated instructions as hints to
  3372. // InstCombine.
  3373. if (VF.isVector())
  3374. truncateToMinimalBitwidths(State);
  3375. // Fix widened non-induction PHIs by setting up the PHI operands.
  3376. if (OrigPHIsToFix.size()) {
  3377. assert(EnableVPlanNativePath &&
  3378. "Unexpected non-induction PHIs for fixup in non VPlan-native path");
  3379. fixNonInductionPHIs(State);
  3380. }
  3381. // At this point every instruction in the original loop is widened to a
  3382. // vector form. Now we need to fix the recurrences in the loop. These PHI
  3383. // nodes are currently empty because we did not want to introduce cycles.
  3384. // This is the second stage of vectorizing recurrences.
  3385. fixCrossIterationPHIs(State);
  3386. // Forget the original basic block.
  3387. PSE.getSE()->forgetLoop(OrigLoop);
  3388. // If we inserted an edge from the middle block to the unique exit block,
  3389. // update uses outside the loop (phis) to account for the newly inserted
  3390. // edge.
  3391. if (!Cost->requiresScalarEpilogue(VF)) {
  3392. // Fix-up external users of the induction variables.
  3393. for (auto &Entry : Legal->getInductionVars())
  3394. fixupIVUsers(Entry.first, Entry.second,
  3395. getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
  3396. IVEndValues[Entry.first], LoopMiddleBlock);
  3397. fixLCSSAPHIs(State);
  3398. }
  3399. for (Instruction *PI : PredicatedInstructions)
  3400. sinkScalarOperands(&*PI);
  3401. // Remove redundant induction instructions.
  3402. cse(LoopVectorBody);
  3403. // Set/update profile weights for the vector and remainder loops as original
  3404. // loop iterations are now distributed among them. Note that original loop
  3405. // represented by LoopScalarBody becomes remainder loop after vectorization.
  3406. //
  3407. // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
  3408. // end up getting slightly roughened result but that should be OK since
  3409. // profile is not inherently precise anyway. Note also possible bypass of
  3410. // vector code caused by legality checks is ignored, assigning all the weight
  3411. // to the vector loop, optimistically.
  3412. //
  3413. // For scalable vectorization we can't know at compile time how many iterations
  3414. // of the loop are handled in one vector iteration, so instead assume a pessimistic
  3415. // vscale of '1'.
  3416. setProfileInfoAfterUnrolling(
  3417. LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
  3418. LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
  3419. }
  3420. void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
  3421. // In order to support recurrences we need to be able to vectorize Phi nodes.
  3422. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  3423. // stage #2: We now need to fix the recurrences by adding incoming edges to
  3424. // the currently empty PHI nodes. At this point every instruction in the
  3425. // original loop is widened to a vector form so we can use them to construct
  3426. // the incoming edges.
  3427. VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
  3428. for (VPRecipeBase &R : Header->phis()) {
  3429. if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
  3430. fixReduction(ReductionPhi, State);
  3431. else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
  3432. fixFirstOrderRecurrence(FOR, State);
  3433. }
  3434. }
  3435. void InnerLoopVectorizer::fixFirstOrderRecurrence(
  3436. VPFirstOrderRecurrencePHIRecipe *PhiR, VPTransformState &State) {
  3437. // This is the second phase of vectorizing first-order recurrences. An
  3438. // overview of the transformation is described below. Suppose we have the
  3439. // following loop.
  3440. //
  3441. // for (int i = 0; i < n; ++i)
  3442. // b[i] = a[i] - a[i - 1];
  3443. //
  3444. // There is a first-order recurrence on "a". For this loop, the shorthand
  3445. // scalar IR looks like:
  3446. //
  3447. // scalar.ph:
  3448. // s_init = a[-1]
  3449. // br scalar.body
  3450. //
  3451. // scalar.body:
  3452. // i = phi [0, scalar.ph], [i+1, scalar.body]
  3453. // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
  3454. // s2 = a[i]
  3455. // b[i] = s2 - s1
  3456. // br cond, scalar.body, ...
  3457. //
  3458. // In this example, s1 is a recurrence because it's value depends on the
  3459. // previous iteration. In the first phase of vectorization, we created a
  3460. // vector phi v1 for s1. We now complete the vectorization and produce the
  3461. // shorthand vector IR shown below (for VF = 4, UF = 1).
  3462. //
  3463. // vector.ph:
  3464. // v_init = vector(..., ..., ..., a[-1])
  3465. // br vector.body
  3466. //
  3467. // vector.body
  3468. // i = phi [0, vector.ph], [i+4, vector.body]
  3469. // v1 = phi [v_init, vector.ph], [v2, vector.body]
  3470. // v2 = a[i, i+1, i+2, i+3];
  3471. // v3 = vector(v1(3), v2(0, 1, 2))
  3472. // b[i, i+1, i+2, i+3] = v2 - v3
  3473. // br cond, vector.body, middle.block
  3474. //
  3475. // middle.block:
  3476. // x = v2(3)
  3477. // br scalar.ph
  3478. //
  3479. // scalar.ph:
  3480. // s_init = phi [x, middle.block], [a[-1], otherwise]
  3481. // br scalar.body
  3482. //
  3483. // After execution completes the vector loop, we extract the next value of
  3484. // the recurrence (x) to use as the initial value in the scalar loop.
  3485. // Extract the last vector element in the middle block. This will be the
  3486. // initial value for the recurrence when jumping to the scalar loop.
  3487. VPValue *PreviousDef = PhiR->getBackedgeValue();
  3488. Value *Incoming = State.get(PreviousDef, UF - 1);
  3489. auto *ExtractForScalar = Incoming;
  3490. auto *IdxTy = Builder.getInt32Ty();
  3491. if (VF.isVector()) {
  3492. auto *One = ConstantInt::get(IdxTy, 1);
  3493. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  3494. auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
  3495. auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
  3496. ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
  3497. "vector.recur.extract");
  3498. }
  3499. // Extract the second last element in the middle block if the
  3500. // Phi is used outside the loop. We need to extract the phi itself
  3501. // and not the last element (the phi update in the current iteration). This
  3502. // will be the value when jumping to the exit block from the LoopMiddleBlock,
  3503. // when the scalar loop is not run at all.
  3504. Value *ExtractForPhiUsedOutsideLoop = nullptr;
  3505. if (VF.isVector()) {
  3506. auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
  3507. auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
  3508. ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
  3509. Incoming, Idx, "vector.recur.extract.for.phi");
  3510. } else if (UF > 1)
  3511. // When loop is unrolled without vectorizing, initialize
  3512. // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
  3513. // of `Incoming`. This is analogous to the vectorized case above: extracting
  3514. // the second last element when VF > 1.
  3515. ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
  3516. // Fix the initial value of the original recurrence in the scalar loop.
  3517. Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
  3518. PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
  3519. auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
  3520. auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
  3521. for (auto *BB : predecessors(LoopScalarPreHeader)) {
  3522. auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
  3523. Start->addIncoming(Incoming, BB);
  3524. }
  3525. Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
  3526. Phi->setName("scalar.recur");
  3527. // Finally, fix users of the recurrence outside the loop. The users will need
  3528. // either the last value of the scalar recurrence or the last value of the
  3529. // vector recurrence we extracted in the middle block. Since the loop is in
  3530. // LCSSA form, we just need to find all the phi nodes for the original scalar
  3531. // recurrence in the exit block, and then add an edge for the middle block.
  3532. // Note that LCSSA does not imply single entry when the original scalar loop
  3533. // had multiple exiting edges (as we always run the last iteration in the
  3534. // scalar epilogue); in that case, there is no edge from middle to exit and
  3535. // and thus no phis which needed updated.
  3536. if (!Cost->requiresScalarEpilogue(VF))
  3537. for (PHINode &LCSSAPhi : LoopExitBlock->phis())
  3538. if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi))
  3539. LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
  3540. }
  3541. void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
  3542. VPTransformState &State) {
  3543. PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
  3544. // Get it's reduction variable descriptor.
  3545. assert(Legal->isReductionVariable(OrigPhi) &&
  3546. "Unable to find the reduction variable");
  3547. const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
  3548. RecurKind RK = RdxDesc.getRecurrenceKind();
  3549. TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
  3550. Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
  3551. setDebugLocFromInst(ReductionStartValue);
  3552. VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
  3553. // This is the vector-clone of the value that leaves the loop.
  3554. Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
  3555. // Wrap flags are in general invalid after vectorization, clear them.
  3556. clearReductionWrapFlags(RdxDesc, State);
  3557. // Before each round, move the insertion point right between
  3558. // the PHIs and the values we are going to write.
  3559. // This allows us to write both PHINodes and the extractelement
  3560. // instructions.
  3561. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3562. setDebugLocFromInst(LoopExitInst);
  3563. Type *PhiTy = OrigPhi->getType();
  3564. // If tail is folded by masking, the vector value to leave the loop should be
  3565. // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
  3566. // instead of the former. For an inloop reduction the reduction will already
  3567. // be predicated, and does not need to be handled here.
  3568. if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
  3569. for (unsigned Part = 0; Part < UF; ++Part) {
  3570. Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
  3571. Value *Sel = nullptr;
  3572. for (User *U : VecLoopExitInst->users()) {
  3573. if (isa<SelectInst>(U)) {
  3574. assert(!Sel && "Reduction exit feeding two selects");
  3575. Sel = U;
  3576. } else
  3577. assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
  3578. }
  3579. assert(Sel && "Reduction exit feeds no select");
  3580. State.reset(LoopExitInstDef, Sel, Part);
  3581. // If the target can create a predicated operator for the reduction at no
  3582. // extra cost in the loop (for example a predicated vadd), it can be
  3583. // cheaper for the select to remain in the loop than be sunk out of it,
  3584. // and so use the select value for the phi instead of the old
  3585. // LoopExitValue.
  3586. if (PreferPredicatedReductionSelect ||
  3587. TTI->preferPredicatedReductionSelect(
  3588. RdxDesc.getOpcode(), PhiTy,
  3589. TargetTransformInfo::ReductionFlags())) {
  3590. auto *VecRdxPhi =
  3591. cast<PHINode>(State.get(PhiR, Part));
  3592. VecRdxPhi->setIncomingValueForBlock(
  3593. LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
  3594. }
  3595. }
  3596. }
  3597. // If the vector reduction can be performed in a smaller type, we truncate
  3598. // then extend the loop exit value to enable InstCombine to evaluate the
  3599. // entire expression in the smaller type.
  3600. if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
  3601. assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
  3602. Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
  3603. Builder.SetInsertPoint(
  3604. LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
  3605. VectorParts RdxParts(UF);
  3606. for (unsigned Part = 0; Part < UF; ++Part) {
  3607. RdxParts[Part] = State.get(LoopExitInstDef, Part);
  3608. Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3609. Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
  3610. : Builder.CreateZExt(Trunc, VecTy);
  3611. for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
  3612. if (U != Trunc) {
  3613. U->replaceUsesOfWith(RdxParts[Part], Extnd);
  3614. RdxParts[Part] = Extnd;
  3615. }
  3616. }
  3617. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3618. for (unsigned Part = 0; Part < UF; ++Part) {
  3619. RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3620. State.reset(LoopExitInstDef, RdxParts[Part], Part);
  3621. }
  3622. }
  3623. // Reduce all of the unrolled parts into a single vector.
  3624. Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
  3625. unsigned Op = RecurrenceDescriptor::getOpcode(RK);
  3626. // The middle block terminator has already been assigned a DebugLoc here (the
  3627. // OrigLoop's single latch terminator). We want the whole middle block to
  3628. // appear to execute on this line because: (a) it is all compiler generated,
  3629. // (b) these instructions are always executed after evaluating the latch
  3630. // conditional branch, and (c) other passes may add new predecessors which
  3631. // terminate on this line. This is the easiest way to ensure we don't
  3632. // accidentally cause an extra step back into the loop while debugging.
  3633. setDebugLocFromInst(LoopMiddleBlock->getTerminator());
  3634. if (PhiR->isOrdered())
  3635. ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
  3636. else {
  3637. // Floating-point operations should have some FMF to enable the reduction.
  3638. IRBuilderBase::FastMathFlagGuard FMFG(Builder);
  3639. Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
  3640. for (unsigned Part = 1; Part < UF; ++Part) {
  3641. Value *RdxPart = State.get(LoopExitInstDef, Part);
  3642. if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
  3643. ReducedPartRdx = Builder.CreateBinOp(
  3644. (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
  3645. } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
  3646. ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
  3647. ReducedPartRdx, RdxPart);
  3648. else
  3649. ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
  3650. }
  3651. }
  3652. // Create the reduction after the loop. Note that inloop reductions create the
  3653. // target reduction in the loop using a Reduction recipe.
  3654. if (VF.isVector() && !PhiR->isInLoop()) {
  3655. ReducedPartRdx =
  3656. createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
  3657. // If the reduction can be performed in a smaller type, we need to extend
  3658. // the reduction to the wider type before we branch to the original loop.
  3659. if (PhiTy != RdxDesc.getRecurrenceType())
  3660. ReducedPartRdx = RdxDesc.isSigned()
  3661. ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
  3662. : Builder.CreateZExt(ReducedPartRdx, PhiTy);
  3663. }
  3664. PHINode *ResumePhi =
  3665. dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
  3666. // Create a phi node that merges control-flow from the backedge-taken check
  3667. // block and the middle block.
  3668. PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
  3669. LoopScalarPreHeader->getTerminator());
  3670. // If we are fixing reductions in the epilogue loop then we should already
  3671. // have created a bc.merge.rdx Phi after the main vector body. Ensure that
  3672. // we carry over the incoming values correctly.
  3673. for (auto *Incoming : predecessors(LoopScalarPreHeader)) {
  3674. if (Incoming == LoopMiddleBlock)
  3675. BCBlockPhi->addIncoming(ReducedPartRdx, Incoming);
  3676. else if (ResumePhi && llvm::is_contained(ResumePhi->blocks(), Incoming))
  3677. BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(Incoming),
  3678. Incoming);
  3679. else
  3680. BCBlockPhi->addIncoming(ReductionStartValue, Incoming);
  3681. }
  3682. // Set the resume value for this reduction
  3683. ReductionResumeValues.insert({&RdxDesc, BCBlockPhi});
  3684. // Now, we need to fix the users of the reduction variable
  3685. // inside and outside of the scalar remainder loop.
  3686. // We know that the loop is in LCSSA form. We need to update the PHI nodes
  3687. // in the exit blocks. See comment on analogous loop in
  3688. // fixFirstOrderRecurrence for a more complete explaination of the logic.
  3689. if (!Cost->requiresScalarEpilogue(VF))
  3690. for (PHINode &LCSSAPhi : LoopExitBlock->phis())
  3691. if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst))
  3692. LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3693. // Fix the scalar loop reduction variable with the incoming reduction sum
  3694. // from the vector body and from the backedge value.
  3695. int IncomingEdgeBlockIdx =
  3696. OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
  3697. assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
  3698. // Pick the other block.
  3699. int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
  3700. OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
  3701. OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
  3702. }
  3703. void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
  3704. VPTransformState &State) {
  3705. RecurKind RK = RdxDesc.getRecurrenceKind();
  3706. if (RK != RecurKind::Add && RK != RecurKind::Mul)
  3707. return;
  3708. Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
  3709. assert(LoopExitInstr && "null loop exit instruction");
  3710. SmallVector<Instruction *, 8> Worklist;
  3711. SmallPtrSet<Instruction *, 8> Visited;
  3712. Worklist.push_back(LoopExitInstr);
  3713. Visited.insert(LoopExitInstr);
  3714. while (!Worklist.empty()) {
  3715. Instruction *Cur = Worklist.pop_back_val();
  3716. if (isa<OverflowingBinaryOperator>(Cur))
  3717. for (unsigned Part = 0; Part < UF; ++Part) {
  3718. // FIXME: Should not rely on getVPValue at this point.
  3719. Value *V = State.get(State.Plan->getVPValue(Cur, true), Part);
  3720. cast<Instruction>(V)->dropPoisonGeneratingFlags();
  3721. }
  3722. for (User *U : Cur->users()) {
  3723. Instruction *UI = cast<Instruction>(U);
  3724. if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
  3725. Visited.insert(UI).second)
  3726. Worklist.push_back(UI);
  3727. }
  3728. }
  3729. }
  3730. void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
  3731. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3732. if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
  3733. // Some phis were already hand updated by the reduction and recurrence
  3734. // code above, leave them alone.
  3735. continue;
  3736. auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
  3737. // Non-instruction incoming values will have only one value.
  3738. VPLane Lane = VPLane::getFirstLane();
  3739. if (isa<Instruction>(IncomingValue) &&
  3740. !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
  3741. VF))
  3742. Lane = VPLane::getLastLaneForVF(VF);
  3743. // Can be a loop invariant incoming value or the last scalar value to be
  3744. // extracted from the vectorized loop.
  3745. // FIXME: Should not rely on getVPValue at this point.
  3746. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  3747. Value *lastIncomingValue =
  3748. OrigLoop->isLoopInvariant(IncomingValue)
  3749. ? IncomingValue
  3750. : State.get(State.Plan->getVPValue(IncomingValue, true),
  3751. VPIteration(UF - 1, Lane));
  3752. LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
  3753. }
  3754. }
  3755. void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
  3756. // The basic block and loop containing the predicated instruction.
  3757. auto *PredBB = PredInst->getParent();
  3758. auto *VectorLoop = LI->getLoopFor(PredBB);
  3759. // Initialize a worklist with the operands of the predicated instruction.
  3760. SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
  3761. // Holds instructions that we need to analyze again. An instruction may be
  3762. // reanalyzed if we don't yet know if we can sink it or not.
  3763. SmallVector<Instruction *, 8> InstsToReanalyze;
  3764. // Returns true if a given use occurs in the predicated block. Phi nodes use
  3765. // their operands in their corresponding predecessor blocks.
  3766. auto isBlockOfUsePredicated = [&](Use &U) -> bool {
  3767. auto *I = cast<Instruction>(U.getUser());
  3768. BasicBlock *BB = I->getParent();
  3769. if (auto *Phi = dyn_cast<PHINode>(I))
  3770. BB = Phi->getIncomingBlock(
  3771. PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
  3772. return BB == PredBB;
  3773. };
  3774. // Iteratively sink the scalarized operands of the predicated instruction
  3775. // into the block we created for it. When an instruction is sunk, it's
  3776. // operands are then added to the worklist. The algorithm ends after one pass
  3777. // through the worklist doesn't sink a single instruction.
  3778. bool Changed;
  3779. do {
  3780. // Add the instructions that need to be reanalyzed to the worklist, and
  3781. // reset the changed indicator.
  3782. Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
  3783. InstsToReanalyze.clear();
  3784. Changed = false;
  3785. while (!Worklist.empty()) {
  3786. auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
  3787. // We can't sink an instruction if it is a phi node, is not in the loop,
  3788. // or may have side effects.
  3789. if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
  3790. I->mayHaveSideEffects())
  3791. continue;
  3792. // If the instruction is already in PredBB, check if we can sink its
  3793. // operands. In that case, VPlan's sinkScalarOperands() succeeded in
  3794. // sinking the scalar instruction I, hence it appears in PredBB; but it
  3795. // may have failed to sink I's operands (recursively), which we try
  3796. // (again) here.
  3797. if (I->getParent() == PredBB) {
  3798. Worklist.insert(I->op_begin(), I->op_end());
  3799. continue;
  3800. }
  3801. // It's legal to sink the instruction if all its uses occur in the
  3802. // predicated block. Otherwise, there's nothing to do yet, and we may
  3803. // need to reanalyze the instruction.
  3804. if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
  3805. InstsToReanalyze.push_back(I);
  3806. continue;
  3807. }
  3808. // Move the instruction to the beginning of the predicated block, and add
  3809. // it's operands to the worklist.
  3810. I->moveBefore(&*PredBB->getFirstInsertionPt());
  3811. Worklist.insert(I->op_begin(), I->op_end());
  3812. // The sinking may have enabled other instructions to be sunk, so we will
  3813. // need to iterate.
  3814. Changed = true;
  3815. }
  3816. } while (Changed);
  3817. }
  3818. void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
  3819. for (PHINode *OrigPhi : OrigPHIsToFix) {
  3820. VPWidenPHIRecipe *VPPhi =
  3821. cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
  3822. PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
  3823. // Make sure the builder has a valid insert point.
  3824. Builder.SetInsertPoint(NewPhi);
  3825. for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
  3826. VPValue *Inc = VPPhi->getIncomingValue(i);
  3827. VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
  3828. NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
  3829. }
  3830. }
  3831. }
  3832. bool InnerLoopVectorizer::useOrderedReductions(
  3833. const RecurrenceDescriptor &RdxDesc) {
  3834. return Cost->useOrderedReductions(RdxDesc);
  3835. }
  3836. void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
  3837. VPWidenPHIRecipe *PhiR,
  3838. VPTransformState &State) {
  3839. PHINode *P = cast<PHINode>(PN);
  3840. if (EnableVPlanNativePath) {
  3841. // Currently we enter here in the VPlan-native path for non-induction
  3842. // PHIs where all control flow is uniform. We simply widen these PHIs.
  3843. // Create a vector phi with no operands - the vector phi operands will be
  3844. // set at the end of vector code generation.
  3845. Type *VecTy = (State.VF.isScalar())
  3846. ? PN->getType()
  3847. : VectorType::get(PN->getType(), State.VF);
  3848. Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
  3849. State.set(PhiR, VecPhi, 0);
  3850. OrigPHIsToFix.push_back(P);
  3851. return;
  3852. }
  3853. assert(PN->getParent() == OrigLoop->getHeader() &&
  3854. "Non-header phis should have been handled elsewhere");
  3855. // In order to support recurrences we need to be able to vectorize Phi nodes.
  3856. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  3857. // stage #1: We create a new vector PHI node with no incoming edges. We'll use
  3858. // this value when we vectorize all of the instructions that use the PHI.
  3859. assert(!Legal->isReductionVariable(P) &&
  3860. "reductions should be handled elsewhere");
  3861. setDebugLocFromInst(P);
  3862. // This PHINode must be an induction variable.
  3863. // Make sure that we know about it.
  3864. assert(Legal->getInductionVars().count(P) && "Not an induction variable");
  3865. InductionDescriptor II = Legal->getInductionVars().lookup(P);
  3866. const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  3867. auto *IVR = PhiR->getParent()->getPlan()->getCanonicalIV();
  3868. PHINode *CanonicalIV = cast<PHINode>(State.get(IVR, 0));
  3869. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  3870. // which can be found from the original scalar operations.
  3871. switch (II.getKind()) {
  3872. case InductionDescriptor::IK_NoInduction:
  3873. llvm_unreachable("Unknown induction");
  3874. case InductionDescriptor::IK_IntInduction:
  3875. case InductionDescriptor::IK_FpInduction:
  3876. llvm_unreachable("Integer/fp induction is handled elsewhere.");
  3877. case InductionDescriptor::IK_PtrInduction: {
  3878. // Handle the pointer induction variable case.
  3879. assert(P->getType()->isPointerTy() && "Unexpected type.");
  3880. if (Cost->isScalarAfterVectorization(P, State.VF)) {
  3881. // This is the normalized GEP that starts counting at zero.
  3882. Value *PtrInd =
  3883. Builder.CreateSExtOrTrunc(CanonicalIV, II.getStep()->getType());
  3884. // Determine the number of scalars we need to generate for each unroll
  3885. // iteration. If the instruction is uniform, we only need to generate the
  3886. // first lane. Otherwise, we generate all VF values.
  3887. bool IsUniform = vputils::onlyFirstLaneUsed(PhiR);
  3888. assert((IsUniform || !State.VF.isScalable()) &&
  3889. "Cannot scalarize a scalable VF");
  3890. unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
  3891. for (unsigned Part = 0; Part < UF; ++Part) {
  3892. Value *PartStart =
  3893. createStepForVF(Builder, PtrInd->getType(), VF, Part);
  3894. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  3895. Value *Idx = Builder.CreateAdd(
  3896. PartStart, ConstantInt::get(PtrInd->getType(), Lane));
  3897. Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
  3898. Value *SclrGep = emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(),
  3899. DL, II, State.CFG.PrevBB);
  3900. SclrGep->setName("next.gep");
  3901. State.set(PhiR, SclrGep, VPIteration(Part, Lane));
  3902. }
  3903. }
  3904. return;
  3905. }
  3906. assert(isa<SCEVConstant>(II.getStep()) &&
  3907. "Induction step not a SCEV constant!");
  3908. Type *PhiType = II.getStep()->getType();
  3909. // Build a pointer phi
  3910. Value *ScalarStartValue = PhiR->getStartValue()->getLiveInIRValue();
  3911. Type *ScStValueType = ScalarStartValue->getType();
  3912. PHINode *NewPointerPhi =
  3913. PHINode::Create(ScStValueType, 2, "pointer.phi", CanonicalIV);
  3914. NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
  3915. // A pointer induction, performed by using a gep
  3916. BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
  3917. Instruction *InductionLoc = LoopLatch->getTerminator();
  3918. const SCEV *ScalarStep = II.getStep();
  3919. SCEVExpander Exp(*PSE.getSE(), DL, "induction");
  3920. Value *ScalarStepValue =
  3921. Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
  3922. Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
  3923. Value *NumUnrolledElems =
  3924. Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
  3925. Value *InductionGEP = GetElementPtrInst::Create(
  3926. II.getElementType(), NewPointerPhi,
  3927. Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
  3928. InductionLoc);
  3929. NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
  3930. // Create UF many actual address geps that use the pointer
  3931. // phi as base and a vectorized version of the step value
  3932. // (<step*0, ..., step*N>) as offset.
  3933. for (unsigned Part = 0; Part < State.UF; ++Part) {
  3934. Type *VecPhiType = VectorType::get(PhiType, State.VF);
  3935. Value *StartOffsetScalar =
  3936. Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
  3937. Value *StartOffset =
  3938. Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
  3939. // Create a vector of consecutive numbers from zero to VF.
  3940. StartOffset =
  3941. Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
  3942. Value *GEP = Builder.CreateGEP(
  3943. II.getElementType(), NewPointerPhi,
  3944. Builder.CreateMul(
  3945. StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
  3946. "vector.gep"));
  3947. State.set(PhiR, GEP, Part);
  3948. }
  3949. }
  3950. }
  3951. }
  3952. /// A helper function for checking whether an integer division-related
  3953. /// instruction may divide by zero (in which case it must be predicated if
  3954. /// executed conditionally in the scalar code).
  3955. /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
  3956. /// Non-zero divisors that are non compile-time constants will not be
  3957. /// converted into multiplication, so we will still end up scalarizing
  3958. /// the division, but can do so w/o predication.
  3959. static bool mayDivideByZero(Instruction &I) {
  3960. assert((I.getOpcode() == Instruction::UDiv ||
  3961. I.getOpcode() == Instruction::SDiv ||
  3962. I.getOpcode() == Instruction::URem ||
  3963. I.getOpcode() == Instruction::SRem) &&
  3964. "Unexpected instruction");
  3965. Value *Divisor = I.getOperand(1);
  3966. auto *CInt = dyn_cast<ConstantInt>(Divisor);
  3967. return !CInt || CInt->isZero();
  3968. }
  3969. void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
  3970. VPUser &ArgOperands,
  3971. VPTransformState &State) {
  3972. assert(!isa<DbgInfoIntrinsic>(I) &&
  3973. "DbgInfoIntrinsic should have been dropped during VPlan construction");
  3974. setDebugLocFromInst(&I);
  3975. Module *M = I.getParent()->getParent()->getParent();
  3976. auto *CI = cast<CallInst>(&I);
  3977. SmallVector<Type *, 4> Tys;
  3978. for (Value *ArgOperand : CI->args())
  3979. Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
  3980. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  3981. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  3982. // version of the instruction.
  3983. // Is it beneficial to perform intrinsic call compared to lib call?
  3984. bool NeedToScalarize = false;
  3985. InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
  3986. InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
  3987. bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
  3988. assert((UseVectorIntrinsic || !NeedToScalarize) &&
  3989. "Instruction should be scalarized elsewhere.");
  3990. assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
  3991. "Either the intrinsic cost or vector call cost must be valid");
  3992. for (unsigned Part = 0; Part < UF; ++Part) {
  3993. SmallVector<Type *, 2> TysForDecl = {CI->getType()};
  3994. SmallVector<Value *, 4> Args;
  3995. for (auto &I : enumerate(ArgOperands.operands())) {
  3996. // Some intrinsics have a scalar argument - don't replace it with a
  3997. // vector.
  3998. Value *Arg;
  3999. if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
  4000. Arg = State.get(I.value(), Part);
  4001. else {
  4002. Arg = State.get(I.value(), VPIteration(0, 0));
  4003. if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
  4004. TysForDecl.push_back(Arg->getType());
  4005. }
  4006. Args.push_back(Arg);
  4007. }
  4008. Function *VectorF;
  4009. if (UseVectorIntrinsic) {
  4010. // Use vector version of the intrinsic.
  4011. if (VF.isVector())
  4012. TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
  4013. VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
  4014. assert(VectorF && "Can't retrieve vector intrinsic.");
  4015. } else {
  4016. // Use vector version of the function call.
  4017. const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
  4018. #ifndef NDEBUG
  4019. assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
  4020. "Can't create vector function.");
  4021. #endif
  4022. VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
  4023. }
  4024. SmallVector<OperandBundleDef, 1> OpBundles;
  4025. CI->getOperandBundlesAsDefs(OpBundles);
  4026. CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
  4027. if (isa<FPMathOperator>(V))
  4028. V->copyFastMathFlags(CI);
  4029. State.set(Def, V, Part);
  4030. addMetadata(V, &I);
  4031. }
  4032. }
  4033. void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
  4034. // We should not collect Scalars more than once per VF. Right now, this
  4035. // function is called from collectUniformsAndScalars(), which already does
  4036. // this check. Collecting Scalars for VF=1 does not make any sense.
  4037. assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
  4038. "This function should not be visited twice for the same VF");
  4039. SmallSetVector<Instruction *, 8> Worklist;
  4040. // These sets are used to seed the analysis with pointers used by memory
  4041. // accesses that will remain scalar.
  4042. SmallSetVector<Instruction *, 8> ScalarPtrs;
  4043. SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
  4044. auto *Latch = TheLoop->getLoopLatch();
  4045. // A helper that returns true if the use of Ptr by MemAccess will be scalar.
  4046. // The pointer operands of loads and stores will be scalar as long as the
  4047. // memory access is not a gather or scatter operation. The value operand of a
  4048. // store will remain scalar if the store is scalarized.
  4049. auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
  4050. InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
  4051. assert(WideningDecision != CM_Unknown &&
  4052. "Widening decision should be ready at this moment");
  4053. if (auto *Store = dyn_cast<StoreInst>(MemAccess))
  4054. if (Ptr == Store->getValueOperand())
  4055. return WideningDecision == CM_Scalarize;
  4056. assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
  4057. "Ptr is neither a value or pointer operand");
  4058. return WideningDecision != CM_GatherScatter;
  4059. };
  4060. // A helper that returns true if the given value is a bitcast or
  4061. // getelementptr instruction contained in the loop.
  4062. auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
  4063. return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
  4064. isa<GetElementPtrInst>(V)) &&
  4065. !TheLoop->isLoopInvariant(V);
  4066. };
  4067. // A helper that evaluates a memory access's use of a pointer. If the use will
  4068. // be a scalar use and the pointer is only used by memory accesses, we place
  4069. // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
  4070. // PossibleNonScalarPtrs.
  4071. auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
  4072. // We only care about bitcast and getelementptr instructions contained in
  4073. // the loop.
  4074. if (!isLoopVaryingBitCastOrGEP(Ptr))
  4075. return;
  4076. // If the pointer has already been identified as scalar (e.g., if it was
  4077. // also identified as uniform), there's nothing to do.
  4078. auto *I = cast<Instruction>(Ptr);
  4079. if (Worklist.count(I))
  4080. return;
  4081. // If the use of the pointer will be a scalar use, and all users of the
  4082. // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
  4083. // place the pointer in PossibleNonScalarPtrs.
  4084. if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
  4085. return isa<LoadInst>(U) || isa<StoreInst>(U);
  4086. }))
  4087. ScalarPtrs.insert(I);
  4088. else
  4089. PossibleNonScalarPtrs.insert(I);
  4090. };
  4091. // We seed the scalars analysis with three classes of instructions: (1)
  4092. // instructions marked uniform-after-vectorization and (2) bitcast,
  4093. // getelementptr and (pointer) phi instructions used by memory accesses
  4094. // requiring a scalar use.
  4095. //
  4096. // (1) Add to the worklist all instructions that have been identified as
  4097. // uniform-after-vectorization.
  4098. Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
  4099. // (2) Add to the worklist all bitcast and getelementptr instructions used by
  4100. // memory accesses requiring a scalar use. The pointer operands of loads and
  4101. // stores will be scalar as long as the memory accesses is not a gather or
  4102. // scatter operation. The value operand of a store will remain scalar if the
  4103. // store is scalarized.
  4104. for (auto *BB : TheLoop->blocks())
  4105. for (auto &I : *BB) {
  4106. if (auto *Load = dyn_cast<LoadInst>(&I)) {
  4107. evaluatePtrUse(Load, Load->getPointerOperand());
  4108. } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
  4109. evaluatePtrUse(Store, Store->getPointerOperand());
  4110. evaluatePtrUse(Store, Store->getValueOperand());
  4111. }
  4112. }
  4113. for (auto *I : ScalarPtrs)
  4114. if (!PossibleNonScalarPtrs.count(I)) {
  4115. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
  4116. Worklist.insert(I);
  4117. }
  4118. // Insert the forced scalars.
  4119. // FIXME: Currently widenPHIInstruction() often creates a dead vector
  4120. // induction variable when the PHI user is scalarized.
  4121. auto ForcedScalar = ForcedScalars.find(VF);
  4122. if (ForcedScalar != ForcedScalars.end())
  4123. for (auto *I : ForcedScalar->second)
  4124. Worklist.insert(I);
  4125. // Expand the worklist by looking through any bitcasts and getelementptr
  4126. // instructions we've already identified as scalar. This is similar to the
  4127. // expansion step in collectLoopUniforms(); however, here we're only
  4128. // expanding to include additional bitcasts and getelementptr instructions.
  4129. unsigned Idx = 0;
  4130. while (Idx != Worklist.size()) {
  4131. Instruction *Dst = Worklist[Idx++];
  4132. if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
  4133. continue;
  4134. auto *Src = cast<Instruction>(Dst->getOperand(0));
  4135. if (llvm::all_of(Src->users(), [&](User *U) -> bool {
  4136. auto *J = cast<Instruction>(U);
  4137. return !TheLoop->contains(J) || Worklist.count(J) ||
  4138. ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
  4139. isScalarUse(J, Src));
  4140. })) {
  4141. Worklist.insert(Src);
  4142. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
  4143. }
  4144. }
  4145. // An induction variable will remain scalar if all users of the induction
  4146. // variable and induction variable update remain scalar.
  4147. for (auto &Induction : Legal->getInductionVars()) {
  4148. auto *Ind = Induction.first;
  4149. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  4150. // If tail-folding is applied, the primary induction variable will be used
  4151. // to feed a vector compare.
  4152. if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
  4153. continue;
  4154. // Returns true if \p Indvar is a pointer induction that is used directly by
  4155. // load/store instruction \p I.
  4156. auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
  4157. Instruction *I) {
  4158. return Induction.second.getKind() ==
  4159. InductionDescriptor::IK_PtrInduction &&
  4160. (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  4161. Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
  4162. };
  4163. // Determine if all users of the induction variable are scalar after
  4164. // vectorization.
  4165. auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  4166. auto *I = cast<Instruction>(U);
  4167. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
  4168. IsDirectLoadStoreFromPtrIndvar(Ind, I);
  4169. });
  4170. if (!ScalarInd)
  4171. continue;
  4172. // Determine if all users of the induction variable update instruction are
  4173. // scalar after vectorization.
  4174. auto ScalarIndUpdate =
  4175. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  4176. auto *I = cast<Instruction>(U);
  4177. return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
  4178. IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
  4179. });
  4180. if (!ScalarIndUpdate)
  4181. continue;
  4182. // The induction variable and its update instruction will remain scalar.
  4183. Worklist.insert(Ind);
  4184. Worklist.insert(IndUpdate);
  4185. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
  4186. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
  4187. << "\n");
  4188. }
  4189. Scalars[VF].insert(Worklist.begin(), Worklist.end());
  4190. }
  4191. bool LoopVectorizationCostModel::isScalarWithPredication(
  4192. Instruction *I, ElementCount VF) const {
  4193. if (!blockNeedsPredicationForAnyReason(I->getParent()))
  4194. return false;
  4195. switch(I->getOpcode()) {
  4196. default:
  4197. break;
  4198. case Instruction::Load:
  4199. case Instruction::Store: {
  4200. if (!Legal->isMaskRequired(I))
  4201. return false;
  4202. auto *Ptr = getLoadStorePointerOperand(I);
  4203. auto *Ty = getLoadStoreType(I);
  4204. Type *VTy = Ty;
  4205. if (VF.isVector())
  4206. VTy = VectorType::get(Ty, VF);
  4207. const Align Alignment = getLoadStoreAlignment(I);
  4208. return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
  4209. TTI.isLegalMaskedGather(VTy, Alignment))
  4210. : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
  4211. TTI.isLegalMaskedScatter(VTy, Alignment));
  4212. }
  4213. case Instruction::UDiv:
  4214. case Instruction::SDiv:
  4215. case Instruction::SRem:
  4216. case Instruction::URem:
  4217. return mayDivideByZero(*I);
  4218. }
  4219. return false;
  4220. }
  4221. bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
  4222. Instruction *I, ElementCount VF) {
  4223. assert(isAccessInterleaved(I) && "Expecting interleaved access.");
  4224. assert(getWideningDecision(I, VF) == CM_Unknown &&
  4225. "Decision should not be set yet.");
  4226. auto *Group = getInterleavedAccessGroup(I);
  4227. assert(Group && "Must have a group.");
  4228. // If the instruction's allocated size doesn't equal it's type size, it
  4229. // requires padding and will be scalarized.
  4230. auto &DL = I->getModule()->getDataLayout();
  4231. auto *ScalarTy = getLoadStoreType(I);
  4232. if (hasIrregularType(ScalarTy, DL))
  4233. return false;
  4234. // Check if masking is required.
  4235. // A Group may need masking for one of two reasons: it resides in a block that
  4236. // needs predication, or it was decided to use masking to deal with gaps
  4237. // (either a gap at the end of a load-access that may result in a speculative
  4238. // load, or any gaps in a store-access).
  4239. bool PredicatedAccessRequiresMasking =
  4240. blockNeedsPredicationForAnyReason(I->getParent()) &&
  4241. Legal->isMaskRequired(I);
  4242. bool LoadAccessWithGapsRequiresEpilogMasking =
  4243. isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
  4244. !isScalarEpilogueAllowed();
  4245. bool StoreAccessWithGapsRequiresMasking =
  4246. isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
  4247. if (!PredicatedAccessRequiresMasking &&
  4248. !LoadAccessWithGapsRequiresEpilogMasking &&
  4249. !StoreAccessWithGapsRequiresMasking)
  4250. return true;
  4251. // If masked interleaving is required, we expect that the user/target had
  4252. // enabled it, because otherwise it either wouldn't have been created or
  4253. // it should have been invalidated by the CostModel.
  4254. assert(useMaskedInterleavedAccesses(TTI) &&
  4255. "Masked interleave-groups for predicated accesses are not enabled.");
  4256. if (Group->isReverse())
  4257. return false;
  4258. auto *Ty = getLoadStoreType(I);
  4259. const Align Alignment = getLoadStoreAlignment(I);
  4260. return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
  4261. : TTI.isLegalMaskedStore(Ty, Alignment);
  4262. }
  4263. bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
  4264. Instruction *I, ElementCount VF) {
  4265. // Get and ensure we have a valid memory instruction.
  4266. assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
  4267. auto *Ptr = getLoadStorePointerOperand(I);
  4268. auto *ScalarTy = getLoadStoreType(I);
  4269. // In order to be widened, the pointer should be consecutive, first of all.
  4270. if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
  4271. return false;
  4272. // If the instruction is a store located in a predicated block, it will be
  4273. // scalarized.
  4274. if (isScalarWithPredication(I, VF))
  4275. return false;
  4276. // If the instruction's allocated size doesn't equal it's type size, it
  4277. // requires padding and will be scalarized.
  4278. auto &DL = I->getModule()->getDataLayout();
  4279. if (hasIrregularType(ScalarTy, DL))
  4280. return false;
  4281. return true;
  4282. }
  4283. void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
  4284. // We should not collect Uniforms more than once per VF. Right now,
  4285. // this function is called from collectUniformsAndScalars(), which
  4286. // already does this check. Collecting Uniforms for VF=1 does not make any
  4287. // sense.
  4288. assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
  4289. "This function should not be visited twice for the same VF");
  4290. // Visit the list of Uniforms. If we'll not find any uniform value, we'll
  4291. // not analyze again. Uniforms.count(VF) will return 1.
  4292. Uniforms[VF].clear();
  4293. // We now know that the loop is vectorizable!
  4294. // Collect instructions inside the loop that will remain uniform after
  4295. // vectorization.
  4296. // Global values, params and instructions outside of current loop are out of
  4297. // scope.
  4298. auto isOutOfScope = [&](Value *V) -> bool {
  4299. Instruction *I = dyn_cast<Instruction>(V);
  4300. return (!I || !TheLoop->contains(I));
  4301. };
  4302. // Worklist containing uniform instructions demanding lane 0.
  4303. SetVector<Instruction *> Worklist;
  4304. BasicBlock *Latch = TheLoop->getLoopLatch();
  4305. // Add uniform instructions demanding lane 0 to the worklist. Instructions
  4306. // that are scalar with predication must not be considered uniform after
  4307. // vectorization, because that would create an erroneous replicating region
  4308. // where only a single instance out of VF should be formed.
  4309. // TODO: optimize such seldom cases if found important, see PR40816.
  4310. auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
  4311. if (isOutOfScope(I)) {
  4312. LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
  4313. << *I << "\n");
  4314. return;
  4315. }
  4316. if (isScalarWithPredication(I, VF)) {
  4317. LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
  4318. << *I << "\n");
  4319. return;
  4320. }
  4321. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
  4322. Worklist.insert(I);
  4323. };
  4324. // Start with the conditional branch. If the branch condition is an
  4325. // instruction contained in the loop that is only used by the branch, it is
  4326. // uniform.
  4327. auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
  4328. if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
  4329. addToWorklistIfAllowed(Cmp);
  4330. auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
  4331. InstWidening WideningDecision = getWideningDecision(I, VF);
  4332. assert(WideningDecision != CM_Unknown &&
  4333. "Widening decision should be ready at this moment");
  4334. // A uniform memory op is itself uniform. We exclude uniform stores
  4335. // here as they demand the last lane, not the first one.
  4336. if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
  4337. assert(WideningDecision == CM_Scalarize);
  4338. return true;
  4339. }
  4340. return (WideningDecision == CM_Widen ||
  4341. WideningDecision == CM_Widen_Reverse ||
  4342. WideningDecision == CM_Interleave);
  4343. };
  4344. // Returns true if Ptr is the pointer operand of a memory access instruction
  4345. // I, and I is known to not require scalarization.
  4346. auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
  4347. return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
  4348. };
  4349. // Holds a list of values which are known to have at least one uniform use.
  4350. // Note that there may be other uses which aren't uniform. A "uniform use"
  4351. // here is something which only demands lane 0 of the unrolled iterations;
  4352. // it does not imply that all lanes produce the same value (e.g. this is not
  4353. // the usual meaning of uniform)
  4354. SetVector<Value *> HasUniformUse;
  4355. // Scan the loop for instructions which are either a) known to have only
  4356. // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
  4357. for (auto *BB : TheLoop->blocks())
  4358. for (auto &I : *BB) {
  4359. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
  4360. switch (II->getIntrinsicID()) {
  4361. case Intrinsic::sideeffect:
  4362. case Intrinsic::experimental_noalias_scope_decl:
  4363. case Intrinsic::assume:
  4364. case Intrinsic::lifetime_start:
  4365. case Intrinsic::lifetime_end:
  4366. if (TheLoop->hasLoopInvariantOperands(&I))
  4367. addToWorklistIfAllowed(&I);
  4368. break;
  4369. default:
  4370. break;
  4371. }
  4372. }
  4373. // ExtractValue instructions must be uniform, because the operands are
  4374. // known to be loop-invariant.
  4375. if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
  4376. assert(isOutOfScope(EVI->getAggregateOperand()) &&
  4377. "Expected aggregate value to be loop invariant");
  4378. addToWorklistIfAllowed(EVI);
  4379. continue;
  4380. }
  4381. // If there's no pointer operand, there's nothing to do.
  4382. auto *Ptr = getLoadStorePointerOperand(&I);
  4383. if (!Ptr)
  4384. continue;
  4385. // A uniform memory op is itself uniform. We exclude uniform stores
  4386. // here as they demand the last lane, not the first one.
  4387. if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
  4388. addToWorklistIfAllowed(&I);
  4389. if (isUniformDecision(&I, VF)) {
  4390. assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
  4391. HasUniformUse.insert(Ptr);
  4392. }
  4393. }
  4394. // Add to the worklist any operands which have *only* uniform (e.g. lane 0
  4395. // demanding) users. Since loops are assumed to be in LCSSA form, this
  4396. // disallows uses outside the loop as well.
  4397. for (auto *V : HasUniformUse) {
  4398. if (isOutOfScope(V))
  4399. continue;
  4400. auto *I = cast<Instruction>(V);
  4401. auto UsersAreMemAccesses =
  4402. llvm::all_of(I->users(), [&](User *U) -> bool {
  4403. return isVectorizedMemAccessUse(cast<Instruction>(U), V);
  4404. });
  4405. if (UsersAreMemAccesses)
  4406. addToWorklistIfAllowed(I);
  4407. }
  4408. // Expand Worklist in topological order: whenever a new instruction
  4409. // is added , its users should be already inside Worklist. It ensures
  4410. // a uniform instruction will only be used by uniform instructions.
  4411. unsigned idx = 0;
  4412. while (idx != Worklist.size()) {
  4413. Instruction *I = Worklist[idx++];
  4414. for (auto OV : I->operand_values()) {
  4415. // isOutOfScope operands cannot be uniform instructions.
  4416. if (isOutOfScope(OV))
  4417. continue;
  4418. // First order recurrence Phi's should typically be considered
  4419. // non-uniform.
  4420. auto *OP = dyn_cast<PHINode>(OV);
  4421. if (OP && Legal->isFirstOrderRecurrence(OP))
  4422. continue;
  4423. // If all the users of the operand are uniform, then add the
  4424. // operand into the uniform worklist.
  4425. auto *OI = cast<Instruction>(OV);
  4426. if (llvm::all_of(OI->users(), [&](User *U) -> bool {
  4427. auto *J = cast<Instruction>(U);
  4428. return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
  4429. }))
  4430. addToWorklistIfAllowed(OI);
  4431. }
  4432. }
  4433. // For an instruction to be added into Worklist above, all its users inside
  4434. // the loop should also be in Worklist. However, this condition cannot be
  4435. // true for phi nodes that form a cyclic dependence. We must process phi
  4436. // nodes separately. An induction variable will remain uniform if all users
  4437. // of the induction variable and induction variable update remain uniform.
  4438. // The code below handles both pointer and non-pointer induction variables.
  4439. for (auto &Induction : Legal->getInductionVars()) {
  4440. auto *Ind = Induction.first;
  4441. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  4442. // Determine if all users of the induction variable are uniform after
  4443. // vectorization.
  4444. auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  4445. auto *I = cast<Instruction>(U);
  4446. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
  4447. isVectorizedMemAccessUse(I, Ind);
  4448. });
  4449. if (!UniformInd)
  4450. continue;
  4451. // Determine if all users of the induction variable update instruction are
  4452. // uniform after vectorization.
  4453. auto UniformIndUpdate =
  4454. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  4455. auto *I = cast<Instruction>(U);
  4456. return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
  4457. isVectorizedMemAccessUse(I, IndUpdate);
  4458. });
  4459. if (!UniformIndUpdate)
  4460. continue;
  4461. // The induction variable and its update instruction will remain uniform.
  4462. addToWorklistIfAllowed(Ind);
  4463. addToWorklistIfAllowed(IndUpdate);
  4464. }
  4465. Uniforms[VF].insert(Worklist.begin(), Worklist.end());
  4466. }
  4467. bool LoopVectorizationCostModel::runtimeChecksRequired() {
  4468. LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
  4469. if (Legal->getRuntimePointerChecking()->Need) {
  4470. reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
  4471. "runtime pointer checks needed. Enable vectorization of this "
  4472. "loop with '#pragma clang loop vectorize(enable)' when "
  4473. "compiling with -Os/-Oz",
  4474. "CantVersionLoopWithOptForSize", ORE, TheLoop);
  4475. return true;
  4476. }
  4477. if (!PSE.getUnionPredicate().getPredicates().empty()) {
  4478. reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
  4479. "runtime SCEV checks needed. Enable vectorization of this "
  4480. "loop with '#pragma clang loop vectorize(enable)' when "
  4481. "compiling with -Os/-Oz",
  4482. "CantVersionLoopWithOptForSize", ORE, TheLoop);
  4483. return true;
  4484. }
  4485. // FIXME: Avoid specializing for stride==1 instead of bailing out.
  4486. if (!Legal->getLAI()->getSymbolicStrides().empty()) {
  4487. reportVectorizationFailure("Runtime stride check for small trip count",
  4488. "runtime stride == 1 checks needed. Enable vectorization of "
  4489. "this loop without such check by compiling with -Os/-Oz",
  4490. "CantVersionLoopWithOptForSize", ORE, TheLoop);
  4491. return true;
  4492. }
  4493. return false;
  4494. }
  4495. ElementCount
  4496. LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
  4497. if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
  4498. return ElementCount::getScalable(0);
  4499. if (Hints->isScalableVectorizationDisabled()) {
  4500. reportVectorizationInfo("Scalable vectorization is explicitly disabled",
  4501. "ScalableVectorizationDisabled", ORE, TheLoop);
  4502. return ElementCount::getScalable(0);
  4503. }
  4504. LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
  4505. auto MaxScalableVF = ElementCount::getScalable(
  4506. std::numeric_limits<ElementCount::ScalarTy>::max());
  4507. // Test that the loop-vectorizer can legalize all operations for this MaxVF.
  4508. // FIXME: While for scalable vectors this is currently sufficient, this should
  4509. // be replaced by a more detailed mechanism that filters out specific VFs,
  4510. // instead of invalidating vectorization for a whole set of VFs based on the
  4511. // MaxVF.
  4512. // Disable scalable vectorization if the loop contains unsupported reductions.
  4513. if (!canVectorizeReductions(MaxScalableVF)) {
  4514. reportVectorizationInfo(
  4515. "Scalable vectorization not supported for the reduction "
  4516. "operations found in this loop.",
  4517. "ScalableVFUnfeasible", ORE, TheLoop);
  4518. return ElementCount::getScalable(0);
  4519. }
  4520. // Disable scalable vectorization if the loop contains any instructions
  4521. // with element types not supported for scalable vectors.
  4522. if (any_of(ElementTypesInLoop, [&](Type *Ty) {
  4523. return !Ty->isVoidTy() &&
  4524. !this->TTI.isElementTypeLegalForScalableVector(Ty);
  4525. })) {
  4526. reportVectorizationInfo("Scalable vectorization is not supported "
  4527. "for all element types found in this loop.",
  4528. "ScalableVFUnfeasible", ORE, TheLoop);
  4529. return ElementCount::getScalable(0);
  4530. }
  4531. if (Legal->isSafeForAnyVectorWidth())
  4532. return MaxScalableVF;
  4533. // Limit MaxScalableVF by the maximum safe dependence distance.
  4534. Optional<unsigned> MaxVScale = TTI.getMaxVScale();
  4535. if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange))
  4536. MaxVScale =
  4537. TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
  4538. MaxScalableVF = ElementCount::getScalable(
  4539. MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
  4540. if (!MaxScalableVF)
  4541. reportVectorizationInfo(
  4542. "Max legal vector width too small, scalable vectorization "
  4543. "unfeasible.",
  4544. "ScalableVFUnfeasible", ORE, TheLoop);
  4545. return MaxScalableVF;
  4546. }
  4547. FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
  4548. unsigned ConstTripCount, ElementCount UserVF, bool FoldTailByMasking) {
  4549. MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
  4550. unsigned SmallestType, WidestType;
  4551. std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
  4552. // Get the maximum safe dependence distance in bits computed by LAA.
  4553. // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
  4554. // the memory accesses that is most restrictive (involved in the smallest
  4555. // dependence distance).
  4556. unsigned MaxSafeElements =
  4557. PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
  4558. auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
  4559. auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
  4560. LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
  4561. << ".\n");
  4562. LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
  4563. << ".\n");
  4564. // First analyze the UserVF, fall back if the UserVF should be ignored.
  4565. if (UserVF) {
  4566. auto MaxSafeUserVF =
  4567. UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
  4568. if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
  4569. // If `VF=vscale x N` is safe, then so is `VF=N`
  4570. if (UserVF.isScalable())
  4571. return FixedScalableVFPair(
  4572. ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
  4573. else
  4574. return UserVF;
  4575. }
  4576. assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
  4577. // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
  4578. // is better to ignore the hint and let the compiler choose a suitable VF.
  4579. if (!UserVF.isScalable()) {
  4580. LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
  4581. << " is unsafe, clamping to max safe VF="
  4582. << MaxSafeFixedVF << ".\n");
  4583. ORE->emit([&]() {
  4584. return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
  4585. TheLoop->getStartLoc(),
  4586. TheLoop->getHeader())
  4587. << "User-specified vectorization factor "
  4588. << ore::NV("UserVectorizationFactor", UserVF)
  4589. << " is unsafe, clamping to maximum safe vectorization factor "
  4590. << ore::NV("VectorizationFactor", MaxSafeFixedVF);
  4591. });
  4592. return MaxSafeFixedVF;
  4593. }
  4594. if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
  4595. LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
  4596. << " is ignored because scalable vectors are not "
  4597. "available.\n");
  4598. ORE->emit([&]() {
  4599. return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
  4600. TheLoop->getStartLoc(),
  4601. TheLoop->getHeader())
  4602. << "User-specified vectorization factor "
  4603. << ore::NV("UserVectorizationFactor", UserVF)
  4604. << " is ignored because the target does not support scalable "
  4605. "vectors. The compiler will pick a more suitable value.";
  4606. });
  4607. } else {
  4608. LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
  4609. << " is unsafe. Ignoring scalable UserVF.\n");
  4610. ORE->emit([&]() {
  4611. return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
  4612. TheLoop->getStartLoc(),
  4613. TheLoop->getHeader())
  4614. << "User-specified vectorization factor "
  4615. << ore::NV("UserVectorizationFactor", UserVF)
  4616. << " is unsafe. Ignoring the hint to let the compiler pick a "
  4617. "more suitable value.";
  4618. });
  4619. }
  4620. }
  4621. LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
  4622. << " / " << WidestType << " bits.\n");
  4623. FixedScalableVFPair Result(ElementCount::getFixed(1),
  4624. ElementCount::getScalable(0));
  4625. if (auto MaxVF =
  4626. getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
  4627. MaxSafeFixedVF, FoldTailByMasking))
  4628. Result.FixedVF = MaxVF;
  4629. if (auto MaxVF =
  4630. getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
  4631. MaxSafeScalableVF, FoldTailByMasking))
  4632. if (MaxVF.isScalable()) {
  4633. Result.ScalableVF = MaxVF;
  4634. LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
  4635. << "\n");
  4636. }
  4637. return Result;
  4638. }
  4639. FixedScalableVFPair
  4640. LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
  4641. if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
  4642. // TODO: It may by useful to do since it's still likely to be dynamically
  4643. // uniform if the target can skip.
  4644. reportVectorizationFailure(
  4645. "Not inserting runtime ptr check for divergent target",
  4646. "runtime pointer checks needed. Not enabled for divergent target",
  4647. "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
  4648. return FixedScalableVFPair::getNone();
  4649. }
  4650. unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
  4651. LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
  4652. if (TC == 1) {
  4653. reportVectorizationFailure("Single iteration (non) loop",
  4654. "loop trip count is one, irrelevant for vectorization",
  4655. "SingleIterationLoop", ORE, TheLoop);
  4656. return FixedScalableVFPair::getNone();
  4657. }
  4658. switch (ScalarEpilogueStatus) {
  4659. case CM_ScalarEpilogueAllowed:
  4660. return computeFeasibleMaxVF(TC, UserVF, false);
  4661. case CM_ScalarEpilogueNotAllowedUsePredicate:
  4662. LLVM_FALLTHROUGH;
  4663. case CM_ScalarEpilogueNotNeededUsePredicate:
  4664. LLVM_DEBUG(
  4665. dbgs() << "LV: vector predicate hint/switch found.\n"
  4666. << "LV: Not allowing scalar epilogue, creating predicated "
  4667. << "vector loop.\n");
  4668. break;
  4669. case CM_ScalarEpilogueNotAllowedLowTripLoop:
  4670. // fallthrough as a special case of OptForSize
  4671. case CM_ScalarEpilogueNotAllowedOptSize:
  4672. if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
  4673. LLVM_DEBUG(
  4674. dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
  4675. else
  4676. LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
  4677. << "count.\n");
  4678. // Bail if runtime checks are required, which are not good when optimising
  4679. // for size.
  4680. if (runtimeChecksRequired())
  4681. return FixedScalableVFPair::getNone();
  4682. break;
  4683. }
  4684. // The only loops we can vectorize without a scalar epilogue, are loops with
  4685. // a bottom-test and a single exiting block. We'd have to handle the fact
  4686. // that not every instruction executes on the last iteration. This will
  4687. // require a lane mask which varies through the vector loop body. (TODO)
  4688. if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
  4689. // If there was a tail-folding hint/switch, but we can't fold the tail by
  4690. // masking, fallback to a vectorization with a scalar epilogue.
  4691. if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
  4692. LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
  4693. "scalar epilogue instead.\n");
  4694. ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
  4695. return computeFeasibleMaxVF(TC, UserVF, false);
  4696. }
  4697. return FixedScalableVFPair::getNone();
  4698. }
  4699. // Now try the tail folding
  4700. // Invalidate interleave groups that require an epilogue if we can't mask
  4701. // the interleave-group.
  4702. if (!useMaskedInterleavedAccesses(TTI)) {
  4703. assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
  4704. "No decisions should have been taken at this point");
  4705. // Note: There is no need to invalidate any cost modeling decisions here, as
  4706. // non where taken so far.
  4707. InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
  4708. }
  4709. FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF, true);
  4710. // Avoid tail folding if the trip count is known to be a multiple of any VF
  4711. // we chose.
  4712. // FIXME: The condition below pessimises the case for fixed-width vectors,
  4713. // when scalable VFs are also candidates for vectorization.
  4714. if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
  4715. ElementCount MaxFixedVF = MaxFactors.FixedVF;
  4716. assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
  4717. "MaxFixedVF must be a power of 2");
  4718. unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
  4719. : MaxFixedVF.getFixedValue();
  4720. ScalarEvolution *SE = PSE.getSE();
  4721. const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
  4722. const SCEV *ExitCount = SE->getAddExpr(
  4723. BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
  4724. const SCEV *Rem = SE->getURemExpr(
  4725. SE->applyLoopGuards(ExitCount, TheLoop),
  4726. SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
  4727. if (Rem->isZero()) {
  4728. // Accept MaxFixedVF if we do not have a tail.
  4729. LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
  4730. return MaxFactors;
  4731. }
  4732. }
  4733. // For scalable vectors don't use tail folding for low trip counts or
  4734. // optimizing for code size. We only permit this if the user has explicitly
  4735. // requested it.
  4736. if (ScalarEpilogueStatus != CM_ScalarEpilogueNotNeededUsePredicate &&
  4737. ScalarEpilogueStatus != CM_ScalarEpilogueNotAllowedUsePredicate &&
  4738. MaxFactors.ScalableVF.isVector())
  4739. MaxFactors.ScalableVF = ElementCount::getScalable(0);
  4740. // If we don't know the precise trip count, or if the trip count that we
  4741. // found modulo the vectorization factor is not zero, try to fold the tail
  4742. // by masking.
  4743. // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
  4744. if (Legal->prepareToFoldTailByMasking()) {
  4745. FoldTailByMasking = true;
  4746. return MaxFactors;
  4747. }
  4748. // If there was a tail-folding hint/switch, but we can't fold the tail by
  4749. // masking, fallback to a vectorization with a scalar epilogue.
  4750. if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
  4751. LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
  4752. "scalar epilogue instead.\n");
  4753. ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
  4754. return MaxFactors;
  4755. }
  4756. if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
  4757. LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
  4758. return FixedScalableVFPair::getNone();
  4759. }
  4760. if (TC == 0) {
  4761. reportVectorizationFailure(
  4762. "Unable to calculate the loop count due to complex control flow",
  4763. "unable to calculate the loop count due to complex control flow",
  4764. "UnknownLoopCountComplexCFG", ORE, TheLoop);
  4765. return FixedScalableVFPair::getNone();
  4766. }
  4767. reportVectorizationFailure(
  4768. "Cannot optimize for size and vectorize at the same time.",
  4769. "cannot optimize for size and vectorize at the same time. "
  4770. "Enable vectorization of this loop with '#pragma clang loop "
  4771. "vectorize(enable)' when compiling with -Os/-Oz",
  4772. "NoTailLoopWithOptForSize", ORE, TheLoop);
  4773. return FixedScalableVFPair::getNone();
  4774. }
  4775. ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
  4776. unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
  4777. const ElementCount &MaxSafeVF, bool FoldTailByMasking) {
  4778. bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
  4779. TypeSize WidestRegister = TTI.getRegisterBitWidth(
  4780. ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
  4781. : TargetTransformInfo::RGK_FixedWidthVector);
  4782. // Convenience function to return the minimum of two ElementCounts.
  4783. auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
  4784. assert((LHS.isScalable() == RHS.isScalable()) &&
  4785. "Scalable flags must match");
  4786. return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
  4787. };
  4788. // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
  4789. // Note that both WidestRegister and WidestType may not be a powers of 2.
  4790. auto MaxVectorElementCount = ElementCount::get(
  4791. PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
  4792. ComputeScalableMaxVF);
  4793. MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
  4794. LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
  4795. << (MaxVectorElementCount * WidestType) << " bits.\n");
  4796. if (!MaxVectorElementCount) {
  4797. LLVM_DEBUG(dbgs() << "LV: The target has no "
  4798. << (ComputeScalableMaxVF ? "scalable" : "fixed")
  4799. << " vector registers.\n");
  4800. return ElementCount::getFixed(1);
  4801. }
  4802. const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
  4803. if (ConstTripCount &&
  4804. ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
  4805. (!FoldTailByMasking || isPowerOf2_32(ConstTripCount))) {
  4806. // If loop trip count (TC) is known at compile time there is no point in
  4807. // choosing VF greater than TC (as done in the loop below). Select maximum
  4808. // power of two which doesn't exceed TC.
  4809. // If MaxVectorElementCount is scalable, we only fall back on a fixed VF
  4810. // when the TC is less than or equal to the known number of lanes.
  4811. auto ClampedConstTripCount = PowerOf2Floor(ConstTripCount);
  4812. LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
  4813. "exceeding the constant trip count: "
  4814. << ClampedConstTripCount << "\n");
  4815. return ElementCount::getFixed(ClampedConstTripCount);
  4816. }
  4817. ElementCount MaxVF = MaxVectorElementCount;
  4818. if (TTI.shouldMaximizeVectorBandwidth() ||
  4819. (MaximizeBandwidth && isScalarEpilogueAllowed())) {
  4820. auto MaxVectorElementCountMaxBW = ElementCount::get(
  4821. PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
  4822. ComputeScalableMaxVF);
  4823. MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
  4824. // Collect all viable vectorization factors larger than the default MaxVF
  4825. // (i.e. MaxVectorElementCount).
  4826. SmallVector<ElementCount, 8> VFs;
  4827. for (ElementCount VS = MaxVectorElementCount * 2;
  4828. ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
  4829. VFs.push_back(VS);
  4830. // For each VF calculate its register usage.
  4831. auto RUs = calculateRegisterUsage(VFs);
  4832. // Select the largest VF which doesn't require more registers than existing
  4833. // ones.
  4834. for (int i = RUs.size() - 1; i >= 0; --i) {
  4835. bool Selected = true;
  4836. for (auto &pair : RUs[i].MaxLocalUsers) {
  4837. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
  4838. if (pair.second > TargetNumRegisters)
  4839. Selected = false;
  4840. }
  4841. if (Selected) {
  4842. MaxVF = VFs[i];
  4843. break;
  4844. }
  4845. }
  4846. if (ElementCount MinVF =
  4847. TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
  4848. if (ElementCount::isKnownLT(MaxVF, MinVF)) {
  4849. LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
  4850. << ") with target's minimum: " << MinVF << '\n');
  4851. MaxVF = MinVF;
  4852. }
  4853. }
  4854. }
  4855. return MaxVF;
  4856. }
  4857. Optional<unsigned> LoopVectorizationCostModel::getVScaleForTuning() const {
  4858. if (TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
  4859. auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
  4860. auto Min = Attr.getVScaleRangeMin();
  4861. auto Max = Attr.getVScaleRangeMax();
  4862. if (Max && Min == Max)
  4863. return Max;
  4864. }
  4865. return TTI.getVScaleForTuning();
  4866. }
  4867. bool LoopVectorizationCostModel::isMoreProfitable(
  4868. const VectorizationFactor &A, const VectorizationFactor &B) const {
  4869. InstructionCost CostA = A.Cost;
  4870. InstructionCost CostB = B.Cost;
  4871. unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
  4872. if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
  4873. MaxTripCount) {
  4874. // If we are folding the tail and the trip count is a known (possibly small)
  4875. // constant, the trip count will be rounded up to an integer number of
  4876. // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
  4877. // which we compare directly. When not folding the tail, the total cost will
  4878. // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
  4879. // approximated with the per-lane cost below instead of using the tripcount
  4880. // as here.
  4881. auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
  4882. auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
  4883. return RTCostA < RTCostB;
  4884. }
  4885. // Improve estimate for the vector width if it is scalable.
  4886. unsigned EstimatedWidthA = A.Width.getKnownMinValue();
  4887. unsigned EstimatedWidthB = B.Width.getKnownMinValue();
  4888. if (Optional<unsigned> VScale = getVScaleForTuning()) {
  4889. if (A.Width.isScalable())
  4890. EstimatedWidthA *= VScale.getValue();
  4891. if (B.Width.isScalable())
  4892. EstimatedWidthB *= VScale.getValue();
  4893. }
  4894. // Assume vscale may be larger than 1 (or the value being tuned for),
  4895. // so that scalable vectorization is slightly favorable over fixed-width
  4896. // vectorization.
  4897. if (A.Width.isScalable() && !B.Width.isScalable())
  4898. return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
  4899. // To avoid the need for FP division:
  4900. // (CostA / A.Width) < (CostB / B.Width)
  4901. // <=> (CostA * B.Width) < (CostB * A.Width)
  4902. return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
  4903. }
  4904. VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
  4905. const ElementCountSet &VFCandidates) {
  4906. InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
  4907. LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
  4908. assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
  4909. assert(VFCandidates.count(ElementCount::getFixed(1)) &&
  4910. "Expected Scalar VF to be a candidate");
  4911. const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
  4912. VectorizationFactor ChosenFactor = ScalarCost;
  4913. bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
  4914. if (ForceVectorization && VFCandidates.size() > 1) {
  4915. // Ignore scalar width, because the user explicitly wants vectorization.
  4916. // Initialize cost to max so that VF = 2 is, at least, chosen during cost
  4917. // evaluation.
  4918. ChosenFactor.Cost = InstructionCost::getMax();
  4919. }
  4920. SmallVector<InstructionVFPair> InvalidCosts;
  4921. for (const auto &i : VFCandidates) {
  4922. // The cost for scalar VF=1 is already calculated, so ignore it.
  4923. if (i.isScalar())
  4924. continue;
  4925. VectorizationCostTy C = expectedCost(i, &InvalidCosts);
  4926. VectorizationFactor Candidate(i, C.first);
  4927. #ifndef NDEBUG
  4928. unsigned AssumedMinimumVscale = 1;
  4929. if (Optional<unsigned> VScale = getVScaleForTuning())
  4930. AssumedMinimumVscale = VScale.getValue();
  4931. unsigned Width =
  4932. Candidate.Width.isScalable()
  4933. ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
  4934. : Candidate.Width.getFixedValue();
  4935. LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
  4936. << " costs: " << (Candidate.Cost / Width));
  4937. if (i.isScalable())
  4938. LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
  4939. << AssumedMinimumVscale << ")");
  4940. LLVM_DEBUG(dbgs() << ".\n");
  4941. #endif
  4942. if (!C.second && !ForceVectorization) {
  4943. LLVM_DEBUG(
  4944. dbgs() << "LV: Not considering vector loop of width " << i
  4945. << " because it will not generate any vector instructions.\n");
  4946. continue;
  4947. }
  4948. // If profitable add it to ProfitableVF list.
  4949. if (isMoreProfitable(Candidate, ScalarCost))
  4950. ProfitableVFs.push_back(Candidate);
  4951. if (isMoreProfitable(Candidate, ChosenFactor))
  4952. ChosenFactor = Candidate;
  4953. }
  4954. // Emit a report of VFs with invalid costs in the loop.
  4955. if (!InvalidCosts.empty()) {
  4956. // Group the remarks per instruction, keeping the instruction order from
  4957. // InvalidCosts.
  4958. std::map<Instruction *, unsigned> Numbering;
  4959. unsigned I = 0;
  4960. for (auto &Pair : InvalidCosts)
  4961. if (!Numbering.count(Pair.first))
  4962. Numbering[Pair.first] = I++;
  4963. // Sort the list, first on instruction(number) then on VF.
  4964. llvm::sort(InvalidCosts,
  4965. [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
  4966. if (Numbering[A.first] != Numbering[B.first])
  4967. return Numbering[A.first] < Numbering[B.first];
  4968. ElementCountComparator ECC;
  4969. return ECC(A.second, B.second);
  4970. });
  4971. // For a list of ordered instruction-vf pairs:
  4972. // [(load, vf1), (load, vf2), (store, vf1)]
  4973. // Group the instructions together to emit separate remarks for:
  4974. // load (vf1, vf2)
  4975. // store (vf1)
  4976. auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
  4977. auto Subset = ArrayRef<InstructionVFPair>();
  4978. do {
  4979. if (Subset.empty())
  4980. Subset = Tail.take_front(1);
  4981. Instruction *I = Subset.front().first;
  4982. // If the next instruction is different, or if there are no other pairs,
  4983. // emit a remark for the collated subset. e.g.
  4984. // [(load, vf1), (load, vf2))]
  4985. // to emit:
  4986. // remark: invalid costs for 'load' at VF=(vf, vf2)
  4987. if (Subset == Tail || Tail[Subset.size()].first != I) {
  4988. std::string OutString;
  4989. raw_string_ostream OS(OutString);
  4990. assert(!Subset.empty() && "Unexpected empty range");
  4991. OS << "Instruction with invalid costs prevented vectorization at VF=(";
  4992. for (auto &Pair : Subset)
  4993. OS << (Pair.second == Subset.front().second ? "" : ", ")
  4994. << Pair.second;
  4995. OS << "):";
  4996. if (auto *CI = dyn_cast<CallInst>(I))
  4997. OS << " call to " << CI->getCalledFunction()->getName();
  4998. else
  4999. OS << " " << I->getOpcodeName();
  5000. OS.flush();
  5001. reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
  5002. Tail = Tail.drop_front(Subset.size());
  5003. Subset = {};
  5004. } else
  5005. // Grow the subset by one element
  5006. Subset = Tail.take_front(Subset.size() + 1);
  5007. } while (!Tail.empty());
  5008. }
  5009. if (!EnableCondStoresVectorization && NumPredStores) {
  5010. reportVectorizationFailure("There are conditional stores.",
  5011. "store that is conditionally executed prevents vectorization",
  5012. "ConditionalStore", ORE, TheLoop);
  5013. ChosenFactor = ScalarCost;
  5014. }
  5015. LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
  5016. ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
  5017. << "LV: Vectorization seems to be not beneficial, "
  5018. << "but was forced by a user.\n");
  5019. LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
  5020. return ChosenFactor;
  5021. }
  5022. bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
  5023. const Loop &L, ElementCount VF) const {
  5024. // Cross iteration phis such as reductions need special handling and are
  5025. // currently unsupported.
  5026. if (any_of(L.getHeader()->phis(),
  5027. [&](PHINode &Phi) { return Legal->isFirstOrderRecurrence(&Phi); }))
  5028. return false;
  5029. // Phis with uses outside of the loop require special handling and are
  5030. // currently unsupported.
  5031. for (auto &Entry : Legal->getInductionVars()) {
  5032. // Look for uses of the value of the induction at the last iteration.
  5033. Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
  5034. for (User *U : PostInc->users())
  5035. if (!L.contains(cast<Instruction>(U)))
  5036. return false;
  5037. // Look for uses of penultimate value of the induction.
  5038. for (User *U : Entry.first->users())
  5039. if (!L.contains(cast<Instruction>(U)))
  5040. return false;
  5041. }
  5042. // Induction variables that are widened require special handling that is
  5043. // currently not supported.
  5044. if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
  5045. return !(this->isScalarAfterVectorization(Entry.first, VF) ||
  5046. this->isProfitableToScalarize(Entry.first, VF));
  5047. }))
  5048. return false;
  5049. // Epilogue vectorization code has not been auditted to ensure it handles
  5050. // non-latch exits properly. It may be fine, but it needs auditted and
  5051. // tested.
  5052. if (L.getExitingBlock() != L.getLoopLatch())
  5053. return false;
  5054. return true;
  5055. }
  5056. bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
  5057. const ElementCount VF) const {
  5058. // FIXME: We need a much better cost-model to take different parameters such
  5059. // as register pressure, code size increase and cost of extra branches into
  5060. // account. For now we apply a very crude heuristic and only consider loops
  5061. // with vectorization factors larger than a certain value.
  5062. // We also consider epilogue vectorization unprofitable for targets that don't
  5063. // consider interleaving beneficial (eg. MVE).
  5064. if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
  5065. return false;
  5066. // FIXME: We should consider changing the threshold for scalable
  5067. // vectors to take VScaleForTuning into account.
  5068. if (VF.getKnownMinValue() >= EpilogueVectorizationMinVF)
  5069. return true;
  5070. return false;
  5071. }
  5072. VectorizationFactor
  5073. LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
  5074. const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
  5075. VectorizationFactor Result = VectorizationFactor::Disabled();
  5076. if (!EnableEpilogueVectorization) {
  5077. LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
  5078. return Result;
  5079. }
  5080. if (!isScalarEpilogueAllowed()) {
  5081. LLVM_DEBUG(
  5082. dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
  5083. "allowed.\n";);
  5084. return Result;
  5085. }
  5086. // Not really a cost consideration, but check for unsupported cases here to
  5087. // simplify the logic.
  5088. if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
  5089. LLVM_DEBUG(
  5090. dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
  5091. "not a supported candidate.\n";);
  5092. return Result;
  5093. }
  5094. if (EpilogueVectorizationForceVF > 1) {
  5095. LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
  5096. ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
  5097. if (LVP.hasPlanWithVF(ForcedEC))
  5098. return {ForcedEC, 0};
  5099. else {
  5100. LLVM_DEBUG(
  5101. dbgs()
  5102. << "LEV: Epilogue vectorization forced factor is not viable.\n";);
  5103. return Result;
  5104. }
  5105. }
  5106. if (TheLoop->getHeader()->getParent()->hasOptSize() ||
  5107. TheLoop->getHeader()->getParent()->hasMinSize()) {
  5108. LLVM_DEBUG(
  5109. dbgs()
  5110. << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
  5111. return Result;
  5112. }
  5113. if (!isEpilogueVectorizationProfitable(MainLoopVF)) {
  5114. LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
  5115. "this loop\n");
  5116. return Result;
  5117. }
  5118. // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
  5119. // the main loop handles 8 lanes per iteration. We could still benefit from
  5120. // vectorizing the epilogue loop with VF=4.
  5121. ElementCount EstimatedRuntimeVF = MainLoopVF;
  5122. if (MainLoopVF.isScalable()) {
  5123. EstimatedRuntimeVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
  5124. if (Optional<unsigned> VScale = getVScaleForTuning())
  5125. EstimatedRuntimeVF *= VScale.getValue();
  5126. }
  5127. for (auto &NextVF : ProfitableVFs)
  5128. if (((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
  5129. ElementCount::isKnownLT(NextVF.Width, EstimatedRuntimeVF)) ||
  5130. ElementCount::isKnownLT(NextVF.Width, MainLoopVF)) &&
  5131. (Result.Width.isScalar() || isMoreProfitable(NextVF, Result)) &&
  5132. LVP.hasPlanWithVF(NextVF.Width))
  5133. Result = NextVF;
  5134. if (Result != VectorizationFactor::Disabled())
  5135. LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
  5136. << Result.Width << "\n";);
  5137. return Result;
  5138. }
  5139. std::pair<unsigned, unsigned>
  5140. LoopVectorizationCostModel::getSmallestAndWidestTypes() {
  5141. unsigned MinWidth = -1U;
  5142. unsigned MaxWidth = 8;
  5143. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  5144. // For in-loop reductions, no element types are added to ElementTypesInLoop
  5145. // if there are no loads/stores in the loop. In this case, check through the
  5146. // reduction variables to determine the maximum width.
  5147. if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
  5148. // Reset MaxWidth so that we can find the smallest type used by recurrences
  5149. // in the loop.
  5150. MaxWidth = -1U;
  5151. for (auto &PhiDescriptorPair : Legal->getReductionVars()) {
  5152. const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
  5153. // When finding the min width used by the recurrence we need to account
  5154. // for casts on the input operands of the recurrence.
  5155. MaxWidth = std::min<unsigned>(
  5156. MaxWidth, std::min<unsigned>(
  5157. RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
  5158. RdxDesc.getRecurrenceType()->getScalarSizeInBits()));
  5159. }
  5160. } else {
  5161. for (Type *T : ElementTypesInLoop) {
  5162. MinWidth = std::min<unsigned>(
  5163. MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
  5164. MaxWidth = std::max<unsigned>(
  5165. MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
  5166. }
  5167. }
  5168. return {MinWidth, MaxWidth};
  5169. }
  5170. void LoopVectorizationCostModel::collectElementTypesForWidening() {
  5171. ElementTypesInLoop.clear();
  5172. // For each block.
  5173. for (BasicBlock *BB : TheLoop->blocks()) {
  5174. // For each instruction in the loop.
  5175. for (Instruction &I : BB->instructionsWithoutDebug()) {
  5176. Type *T = I.getType();
  5177. // Skip ignored values.
  5178. if (ValuesToIgnore.count(&I))
  5179. continue;
  5180. // Only examine Loads, Stores and PHINodes.
  5181. if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
  5182. continue;
  5183. // Examine PHI nodes that are reduction variables. Update the type to
  5184. // account for the recurrence type.
  5185. if (auto *PN = dyn_cast<PHINode>(&I)) {
  5186. if (!Legal->isReductionVariable(PN))
  5187. continue;
  5188. const RecurrenceDescriptor &RdxDesc =
  5189. Legal->getReductionVars().find(PN)->second;
  5190. if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
  5191. TTI.preferInLoopReduction(RdxDesc.getOpcode(),
  5192. RdxDesc.getRecurrenceType(),
  5193. TargetTransformInfo::ReductionFlags()))
  5194. continue;
  5195. T = RdxDesc.getRecurrenceType();
  5196. }
  5197. // Examine the stored values.
  5198. if (auto *ST = dyn_cast<StoreInst>(&I))
  5199. T = ST->getValueOperand()->getType();
  5200. assert(T->isSized() &&
  5201. "Expected the load/store/recurrence type to be sized");
  5202. ElementTypesInLoop.insert(T);
  5203. }
  5204. }
  5205. }
  5206. unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
  5207. unsigned LoopCost) {
  5208. // -- The interleave heuristics --
  5209. // We interleave the loop in order to expose ILP and reduce the loop overhead.
  5210. // There are many micro-architectural considerations that we can't predict
  5211. // at this level. For example, frontend pressure (on decode or fetch) due to
  5212. // code size, or the number and capabilities of the execution ports.
  5213. //
  5214. // We use the following heuristics to select the interleave count:
  5215. // 1. If the code has reductions, then we interleave to break the cross
  5216. // iteration dependency.
  5217. // 2. If the loop is really small, then we interleave to reduce the loop
  5218. // overhead.
  5219. // 3. We don't interleave if we think that we will spill registers to memory
  5220. // due to the increased register pressure.
  5221. if (!isScalarEpilogueAllowed())
  5222. return 1;
  5223. // We used the distance for the interleave count.
  5224. if (Legal->getMaxSafeDepDistBytes() != -1U)
  5225. return 1;
  5226. auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
  5227. const bool HasReductions = !Legal->getReductionVars().empty();
  5228. // Do not interleave loops with a relatively small known or estimated trip
  5229. // count. But we will interleave when InterleaveSmallLoopScalarReduction is
  5230. // enabled, and the code has scalar reductions(HasReductions && VF = 1),
  5231. // because with the above conditions interleaving can expose ILP and break
  5232. // cross iteration dependences for reductions.
  5233. if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
  5234. !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
  5235. return 1;
  5236. // If we did not calculate the cost for VF (because the user selected the VF)
  5237. // then we calculate the cost of VF here.
  5238. if (LoopCost == 0) {
  5239. InstructionCost C = expectedCost(VF).first;
  5240. assert(C.isValid() && "Expected to have chosen a VF with valid cost");
  5241. LoopCost = *C.getValue();
  5242. // Loop body is free and there is no need for interleaving.
  5243. if (LoopCost == 0)
  5244. return 1;
  5245. }
  5246. RegisterUsage R = calculateRegisterUsage({VF})[0];
  5247. // We divide by these constants so assume that we have at least one
  5248. // instruction that uses at least one register.
  5249. for (auto& pair : R.MaxLocalUsers) {
  5250. pair.second = std::max(pair.second, 1U);
  5251. }
  5252. // We calculate the interleave count using the following formula.
  5253. // Subtract the number of loop invariants from the number of available
  5254. // registers. These registers are used by all of the interleaved instances.
  5255. // Next, divide the remaining registers by the number of registers that is
  5256. // required by the loop, in order to estimate how many parallel instances
  5257. // fit without causing spills. All of this is rounded down if necessary to be
  5258. // a power of two. We want power of two interleave count to simplify any
  5259. // addressing operations or alignment considerations.
  5260. // We also want power of two interleave counts to ensure that the induction
  5261. // variable of the vector loop wraps to zero, when tail is folded by masking;
  5262. // this currently happens when OptForSize, in which case IC is set to 1 above.
  5263. unsigned IC = UINT_MAX;
  5264. for (auto& pair : R.MaxLocalUsers) {
  5265. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
  5266. LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
  5267. << " registers of "
  5268. << TTI.getRegisterClassName(pair.first) << " register class\n");
  5269. if (VF.isScalar()) {
  5270. if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
  5271. TargetNumRegisters = ForceTargetNumScalarRegs;
  5272. } else {
  5273. if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
  5274. TargetNumRegisters = ForceTargetNumVectorRegs;
  5275. }
  5276. unsigned MaxLocalUsers = pair.second;
  5277. unsigned LoopInvariantRegs = 0;
  5278. if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
  5279. LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
  5280. unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
  5281. // Don't count the induction variable as interleaved.
  5282. if (EnableIndVarRegisterHeur) {
  5283. TmpIC =
  5284. PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
  5285. std::max(1U, (MaxLocalUsers - 1)));
  5286. }
  5287. IC = std::min(IC, TmpIC);
  5288. }
  5289. // Clamp the interleave ranges to reasonable counts.
  5290. unsigned MaxInterleaveCount =
  5291. TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
  5292. // Check if the user has overridden the max.
  5293. if (VF.isScalar()) {
  5294. if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
  5295. MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
  5296. } else {
  5297. if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
  5298. MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
  5299. }
  5300. // If trip count is known or estimated compile time constant, limit the
  5301. // interleave count to be less than the trip count divided by VF, provided it
  5302. // is at least 1.
  5303. //
  5304. // For scalable vectors we can't know if interleaving is beneficial. It may
  5305. // not be beneficial for small loops if none of the lanes in the second vector
  5306. // iterations is enabled. However, for larger loops, there is likely to be a
  5307. // similar benefit as for fixed-width vectors. For now, we choose to leave
  5308. // the InterleaveCount as if vscale is '1', although if some information about
  5309. // the vector is known (e.g. min vector size), we can make a better decision.
  5310. if (BestKnownTC) {
  5311. MaxInterleaveCount =
  5312. std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
  5313. // Make sure MaxInterleaveCount is greater than 0.
  5314. MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
  5315. }
  5316. assert(MaxInterleaveCount > 0 &&
  5317. "Maximum interleave count must be greater than 0");
  5318. // Clamp the calculated IC to be between the 1 and the max interleave count
  5319. // that the target and trip count allows.
  5320. if (IC > MaxInterleaveCount)
  5321. IC = MaxInterleaveCount;
  5322. else
  5323. // Make sure IC is greater than 0.
  5324. IC = std::max(1u, IC);
  5325. assert(IC > 0 && "Interleave count must be greater than 0.");
  5326. // Interleave if we vectorized this loop and there is a reduction that could
  5327. // benefit from interleaving.
  5328. if (VF.isVector() && HasReductions) {
  5329. LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
  5330. return IC;
  5331. }
  5332. // Note that if we've already vectorized the loop we will have done the
  5333. // runtime check and so interleaving won't require further checks.
  5334. bool InterleavingRequiresRuntimePointerCheck =
  5335. (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
  5336. // We want to interleave small loops in order to reduce the loop overhead and
  5337. // potentially expose ILP opportunities.
  5338. LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
  5339. << "LV: IC is " << IC << '\n'
  5340. << "LV: VF is " << VF << '\n');
  5341. const bool AggressivelyInterleaveReductions =
  5342. TTI.enableAggressiveInterleaving(HasReductions);
  5343. if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
  5344. // We assume that the cost overhead is 1 and we use the cost model
  5345. // to estimate the cost of the loop and interleave until the cost of the
  5346. // loop overhead is about 5% of the cost of the loop.
  5347. unsigned SmallIC =
  5348. std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
  5349. // Interleave until store/load ports (estimated by max interleave count) are
  5350. // saturated.
  5351. unsigned NumStores = Legal->getNumStores();
  5352. unsigned NumLoads = Legal->getNumLoads();
  5353. unsigned StoresIC = IC / (NumStores ? NumStores : 1);
  5354. unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
  5355. // There is little point in interleaving for reductions containing selects
  5356. // and compares when VF=1 since it may just create more overhead than it's
  5357. // worth for loops with small trip counts. This is because we still have to
  5358. // do the final reduction after the loop.
  5359. bool HasSelectCmpReductions =
  5360. HasReductions &&
  5361. any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
  5362. const RecurrenceDescriptor &RdxDesc = Reduction.second;
  5363. return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
  5364. RdxDesc.getRecurrenceKind());
  5365. });
  5366. if (HasSelectCmpReductions) {
  5367. LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
  5368. return 1;
  5369. }
  5370. // If we have a scalar reduction (vector reductions are already dealt with
  5371. // by this point), we can increase the critical path length if the loop
  5372. // we're interleaving is inside another loop. For tree-wise reductions
  5373. // set the limit to 2, and for ordered reductions it's best to disable
  5374. // interleaving entirely.
  5375. if (HasReductions && TheLoop->getLoopDepth() > 1) {
  5376. bool HasOrderedReductions =
  5377. any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
  5378. const RecurrenceDescriptor &RdxDesc = Reduction.second;
  5379. return RdxDesc.isOrdered();
  5380. });
  5381. if (HasOrderedReductions) {
  5382. LLVM_DEBUG(
  5383. dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
  5384. return 1;
  5385. }
  5386. unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
  5387. SmallIC = std::min(SmallIC, F);
  5388. StoresIC = std::min(StoresIC, F);
  5389. LoadsIC = std::min(LoadsIC, F);
  5390. }
  5391. if (EnableLoadStoreRuntimeInterleave &&
  5392. std::max(StoresIC, LoadsIC) > SmallIC) {
  5393. LLVM_DEBUG(
  5394. dbgs() << "LV: Interleaving to saturate store or load ports.\n");
  5395. return std::max(StoresIC, LoadsIC);
  5396. }
  5397. // If there are scalar reductions and TTI has enabled aggressive
  5398. // interleaving for reductions, we will interleave to expose ILP.
  5399. if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
  5400. AggressivelyInterleaveReductions) {
  5401. LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
  5402. // Interleave no less than SmallIC but not as aggressive as the normal IC
  5403. // to satisfy the rare situation when resources are too limited.
  5404. return std::max(IC / 2, SmallIC);
  5405. } else {
  5406. LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
  5407. return SmallIC;
  5408. }
  5409. }
  5410. // Interleave if this is a large loop (small loops are already dealt with by
  5411. // this point) that could benefit from interleaving.
  5412. if (AggressivelyInterleaveReductions) {
  5413. LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
  5414. return IC;
  5415. }
  5416. LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
  5417. return 1;
  5418. }
  5419. SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
  5420. LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
  5421. // This function calculates the register usage by measuring the highest number
  5422. // of values that are alive at a single location. Obviously, this is a very
  5423. // rough estimation. We scan the loop in a topological order in order and
  5424. // assign a number to each instruction. We use RPO to ensure that defs are
  5425. // met before their users. We assume that each instruction that has in-loop
  5426. // users starts an interval. We record every time that an in-loop value is
  5427. // used, so we have a list of the first and last occurrences of each
  5428. // instruction. Next, we transpose this data structure into a multi map that
  5429. // holds the list of intervals that *end* at a specific location. This multi
  5430. // map allows us to perform a linear search. We scan the instructions linearly
  5431. // and record each time that a new interval starts, by placing it in a set.
  5432. // If we find this value in the multi-map then we remove it from the set.
  5433. // The max register usage is the maximum size of the set.
  5434. // We also search for instructions that are defined outside the loop, but are
  5435. // used inside the loop. We need this number separately from the max-interval
  5436. // usage number because when we unroll, loop-invariant values do not take
  5437. // more register.
  5438. LoopBlocksDFS DFS(TheLoop);
  5439. DFS.perform(LI);
  5440. RegisterUsage RU;
  5441. // Each 'key' in the map opens a new interval. The values
  5442. // of the map are the index of the 'last seen' usage of the
  5443. // instruction that is the key.
  5444. using IntervalMap = DenseMap<Instruction *, unsigned>;
  5445. // Maps instruction to its index.
  5446. SmallVector<Instruction *, 64> IdxToInstr;
  5447. // Marks the end of each interval.
  5448. IntervalMap EndPoint;
  5449. // Saves the list of instruction indices that are used in the loop.
  5450. SmallPtrSet<Instruction *, 8> Ends;
  5451. // Saves the list of values that are used in the loop but are
  5452. // defined outside the loop, such as arguments and constants.
  5453. SmallPtrSet<Value *, 8> LoopInvariants;
  5454. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  5455. for (Instruction &I : BB->instructionsWithoutDebug()) {
  5456. IdxToInstr.push_back(&I);
  5457. // Save the end location of each USE.
  5458. for (Value *U : I.operands()) {
  5459. auto *Instr = dyn_cast<Instruction>(U);
  5460. // Ignore non-instruction values such as arguments, constants, etc.
  5461. if (!Instr)
  5462. continue;
  5463. // If this instruction is outside the loop then record it and continue.
  5464. if (!TheLoop->contains(Instr)) {
  5465. LoopInvariants.insert(Instr);
  5466. continue;
  5467. }
  5468. // Overwrite previous end points.
  5469. EndPoint[Instr] = IdxToInstr.size();
  5470. Ends.insert(Instr);
  5471. }
  5472. }
  5473. }
  5474. // Saves the list of intervals that end with the index in 'key'.
  5475. using InstrList = SmallVector<Instruction *, 2>;
  5476. DenseMap<unsigned, InstrList> TransposeEnds;
  5477. // Transpose the EndPoints to a list of values that end at each index.
  5478. for (auto &Interval : EndPoint)
  5479. TransposeEnds[Interval.second].push_back(Interval.first);
  5480. SmallPtrSet<Instruction *, 8> OpenIntervals;
  5481. SmallVector<RegisterUsage, 8> RUs(VFs.size());
  5482. SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
  5483. LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
  5484. // A lambda that gets the register usage for the given type and VF.
  5485. const auto &TTICapture = TTI;
  5486. auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
  5487. if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
  5488. return 0;
  5489. InstructionCost::CostType RegUsage =
  5490. *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
  5491. assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
  5492. "Nonsensical values for register usage.");
  5493. return RegUsage;
  5494. };
  5495. for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
  5496. Instruction *I = IdxToInstr[i];
  5497. // Remove all of the instructions that end at this location.
  5498. InstrList &List = TransposeEnds[i];
  5499. for (Instruction *ToRemove : List)
  5500. OpenIntervals.erase(ToRemove);
  5501. // Ignore instructions that are never used within the loop.
  5502. if (!Ends.count(I))
  5503. continue;
  5504. // Skip ignored values.
  5505. if (ValuesToIgnore.count(I))
  5506. continue;
  5507. // For each VF find the maximum usage of registers.
  5508. for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
  5509. // Count the number of live intervals.
  5510. SmallMapVector<unsigned, unsigned, 4> RegUsage;
  5511. if (VFs[j].isScalar()) {
  5512. for (auto Inst : OpenIntervals) {
  5513. unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
  5514. if (RegUsage.find(ClassID) == RegUsage.end())
  5515. RegUsage[ClassID] = 1;
  5516. else
  5517. RegUsage[ClassID] += 1;
  5518. }
  5519. } else {
  5520. collectUniformsAndScalars(VFs[j]);
  5521. for (auto Inst : OpenIntervals) {
  5522. // Skip ignored values for VF > 1.
  5523. if (VecValuesToIgnore.count(Inst))
  5524. continue;
  5525. if (isScalarAfterVectorization(Inst, VFs[j])) {
  5526. unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
  5527. if (RegUsage.find(ClassID) == RegUsage.end())
  5528. RegUsage[ClassID] = 1;
  5529. else
  5530. RegUsage[ClassID] += 1;
  5531. } else {
  5532. unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
  5533. if (RegUsage.find(ClassID) == RegUsage.end())
  5534. RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
  5535. else
  5536. RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
  5537. }
  5538. }
  5539. }
  5540. for (auto& pair : RegUsage) {
  5541. if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
  5542. MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
  5543. else
  5544. MaxUsages[j][pair.first] = pair.second;
  5545. }
  5546. }
  5547. LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
  5548. << OpenIntervals.size() << '\n');
  5549. // Add the current instruction to the list of open intervals.
  5550. OpenIntervals.insert(I);
  5551. }
  5552. for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
  5553. SmallMapVector<unsigned, unsigned, 4> Invariant;
  5554. for (auto Inst : LoopInvariants) {
  5555. unsigned Usage =
  5556. VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
  5557. unsigned ClassID =
  5558. TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
  5559. if (Invariant.find(ClassID) == Invariant.end())
  5560. Invariant[ClassID] = Usage;
  5561. else
  5562. Invariant[ClassID] += Usage;
  5563. }
  5564. LLVM_DEBUG({
  5565. dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
  5566. dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
  5567. << " item\n";
  5568. for (const auto &pair : MaxUsages[i]) {
  5569. dbgs() << "LV(REG): RegisterClass: "
  5570. << TTI.getRegisterClassName(pair.first) << ", " << pair.second
  5571. << " registers\n";
  5572. }
  5573. dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
  5574. << " item\n";
  5575. for (const auto &pair : Invariant) {
  5576. dbgs() << "LV(REG): RegisterClass: "
  5577. << TTI.getRegisterClassName(pair.first) << ", " << pair.second
  5578. << " registers\n";
  5579. }
  5580. });
  5581. RU.LoopInvariantRegs = Invariant;
  5582. RU.MaxLocalUsers = MaxUsages[i];
  5583. RUs[i] = RU;
  5584. }
  5585. return RUs;
  5586. }
  5587. bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
  5588. ElementCount VF) {
  5589. // TODO: Cost model for emulated masked load/store is completely
  5590. // broken. This hack guides the cost model to use an artificially
  5591. // high enough value to practically disable vectorization with such
  5592. // operations, except where previously deployed legality hack allowed
  5593. // using very low cost values. This is to avoid regressions coming simply
  5594. // from moving "masked load/store" check from legality to cost model.
  5595. // Masked Load/Gather emulation was previously never allowed.
  5596. // Limited number of Masked Store/Scatter emulation was allowed.
  5597. assert(isPredicatedInst(I, VF) && "Expecting a scalar emulated instruction");
  5598. return isa<LoadInst>(I) ||
  5599. (isa<StoreInst>(I) &&
  5600. NumPredStores > NumberOfStoresToPredicate);
  5601. }
  5602. void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
  5603. // If we aren't vectorizing the loop, or if we've already collected the
  5604. // instructions to scalarize, there's nothing to do. Collection may already
  5605. // have occurred if we have a user-selected VF and are now computing the
  5606. // expected cost for interleaving.
  5607. if (VF.isScalar() || VF.isZero() ||
  5608. InstsToScalarize.find(VF) != InstsToScalarize.end())
  5609. return;
  5610. // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
  5611. // not profitable to scalarize any instructions, the presence of VF in the
  5612. // map will indicate that we've analyzed it already.
  5613. ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
  5614. // Find all the instructions that are scalar with predication in the loop and
  5615. // determine if it would be better to not if-convert the blocks they are in.
  5616. // If so, we also record the instructions to scalarize.
  5617. for (BasicBlock *BB : TheLoop->blocks()) {
  5618. if (!blockNeedsPredicationForAnyReason(BB))
  5619. continue;
  5620. for (Instruction &I : *BB)
  5621. if (isScalarWithPredication(&I, VF)) {
  5622. ScalarCostsTy ScalarCosts;
  5623. // Do not apply discount if scalable, because that would lead to
  5624. // invalid scalarization costs.
  5625. // Do not apply discount logic if hacked cost is needed
  5626. // for emulated masked memrefs.
  5627. if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I, VF) &&
  5628. computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
  5629. ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
  5630. // Remember that BB will remain after vectorization.
  5631. PredicatedBBsAfterVectorization.insert(BB);
  5632. }
  5633. }
  5634. }
  5635. int LoopVectorizationCostModel::computePredInstDiscount(
  5636. Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
  5637. assert(!isUniformAfterVectorization(PredInst, VF) &&
  5638. "Instruction marked uniform-after-vectorization will be predicated");
  5639. // Initialize the discount to zero, meaning that the scalar version and the
  5640. // vector version cost the same.
  5641. InstructionCost Discount = 0;
  5642. // Holds instructions to analyze. The instructions we visit are mapped in
  5643. // ScalarCosts. Those instructions are the ones that would be scalarized if
  5644. // we find that the scalar version costs less.
  5645. SmallVector<Instruction *, 8> Worklist;
  5646. // Returns true if the given instruction can be scalarized.
  5647. auto canBeScalarized = [&](Instruction *I) -> bool {
  5648. // We only attempt to scalarize instructions forming a single-use chain
  5649. // from the original predicated block that would otherwise be vectorized.
  5650. // Although not strictly necessary, we give up on instructions we know will
  5651. // already be scalar to avoid traversing chains that are unlikely to be
  5652. // beneficial.
  5653. if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
  5654. isScalarAfterVectorization(I, VF))
  5655. return false;
  5656. // If the instruction is scalar with predication, it will be analyzed
  5657. // separately. We ignore it within the context of PredInst.
  5658. if (isScalarWithPredication(I, VF))
  5659. return false;
  5660. // If any of the instruction's operands are uniform after vectorization,
  5661. // the instruction cannot be scalarized. This prevents, for example, a
  5662. // masked load from being scalarized.
  5663. //
  5664. // We assume we will only emit a value for lane zero of an instruction
  5665. // marked uniform after vectorization, rather than VF identical values.
  5666. // Thus, if we scalarize an instruction that uses a uniform, we would
  5667. // create uses of values corresponding to the lanes we aren't emitting code
  5668. // for. This behavior can be changed by allowing getScalarValue to clone
  5669. // the lane zero values for uniforms rather than asserting.
  5670. for (Use &U : I->operands())
  5671. if (auto *J = dyn_cast<Instruction>(U.get()))
  5672. if (isUniformAfterVectorization(J, VF))
  5673. return false;
  5674. // Otherwise, we can scalarize the instruction.
  5675. return true;
  5676. };
  5677. // Compute the expected cost discount from scalarizing the entire expression
  5678. // feeding the predicated instruction. We currently only consider expressions
  5679. // that are single-use instruction chains.
  5680. Worklist.push_back(PredInst);
  5681. while (!Worklist.empty()) {
  5682. Instruction *I = Worklist.pop_back_val();
  5683. // If we've already analyzed the instruction, there's nothing to do.
  5684. if (ScalarCosts.find(I) != ScalarCosts.end())
  5685. continue;
  5686. // Compute the cost of the vector instruction. Note that this cost already
  5687. // includes the scalarization overhead of the predicated instruction.
  5688. InstructionCost VectorCost = getInstructionCost(I, VF).first;
  5689. // Compute the cost of the scalarized instruction. This cost is the cost of
  5690. // the instruction as if it wasn't if-converted and instead remained in the
  5691. // predicated block. We will scale this cost by block probability after
  5692. // computing the scalarization overhead.
  5693. InstructionCost ScalarCost =
  5694. VF.getFixedValue() *
  5695. getInstructionCost(I, ElementCount::getFixed(1)).first;
  5696. // Compute the scalarization overhead of needed insertelement instructions
  5697. // and phi nodes.
  5698. if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
  5699. ScalarCost += TTI.getScalarizationOverhead(
  5700. cast<VectorType>(ToVectorTy(I->getType(), VF)),
  5701. APInt::getAllOnes(VF.getFixedValue()), true, false);
  5702. ScalarCost +=
  5703. VF.getFixedValue() *
  5704. TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
  5705. }
  5706. // Compute the scalarization overhead of needed extractelement
  5707. // instructions. For each of the instruction's operands, if the operand can
  5708. // be scalarized, add it to the worklist; otherwise, account for the
  5709. // overhead.
  5710. for (Use &U : I->operands())
  5711. if (auto *J = dyn_cast<Instruction>(U.get())) {
  5712. assert(VectorType::isValidElementType(J->getType()) &&
  5713. "Instruction has non-scalar type");
  5714. if (canBeScalarized(J))
  5715. Worklist.push_back(J);
  5716. else if (needsExtract(J, VF)) {
  5717. ScalarCost += TTI.getScalarizationOverhead(
  5718. cast<VectorType>(ToVectorTy(J->getType(), VF)),
  5719. APInt::getAllOnes(VF.getFixedValue()), false, true);
  5720. }
  5721. }
  5722. // Scale the total scalar cost by block probability.
  5723. ScalarCost /= getReciprocalPredBlockProb();
  5724. // Compute the discount. A non-negative discount means the vector version
  5725. // of the instruction costs more, and scalarizing would be beneficial.
  5726. Discount += VectorCost - ScalarCost;
  5727. ScalarCosts[I] = ScalarCost;
  5728. }
  5729. return *Discount.getValue();
  5730. }
  5731. LoopVectorizationCostModel::VectorizationCostTy
  5732. LoopVectorizationCostModel::expectedCost(
  5733. ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
  5734. VectorizationCostTy Cost;
  5735. // For each block.
  5736. for (BasicBlock *BB : TheLoop->blocks()) {
  5737. VectorizationCostTy BlockCost;
  5738. // For each instruction in the old loop.
  5739. for (Instruction &I : BB->instructionsWithoutDebug()) {
  5740. // Skip ignored values.
  5741. if (ValuesToIgnore.count(&I) ||
  5742. (VF.isVector() && VecValuesToIgnore.count(&I)))
  5743. continue;
  5744. VectorizationCostTy C = getInstructionCost(&I, VF);
  5745. // Check if we should override the cost.
  5746. if (C.first.isValid() &&
  5747. ForceTargetInstructionCost.getNumOccurrences() > 0)
  5748. C.first = InstructionCost(ForceTargetInstructionCost);
  5749. // Keep a list of instructions with invalid costs.
  5750. if (Invalid && !C.first.isValid())
  5751. Invalid->emplace_back(&I, VF);
  5752. BlockCost.first += C.first;
  5753. BlockCost.second |= C.second;
  5754. LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
  5755. << " for VF " << VF << " For instruction: " << I
  5756. << '\n');
  5757. }
  5758. // If we are vectorizing a predicated block, it will have been
  5759. // if-converted. This means that the block's instructions (aside from
  5760. // stores and instructions that may divide by zero) will now be
  5761. // unconditionally executed. For the scalar case, we may not always execute
  5762. // the predicated block, if it is an if-else block. Thus, scale the block's
  5763. // cost by the probability of executing it. blockNeedsPredication from
  5764. // Legal is used so as to not include all blocks in tail folded loops.
  5765. if (VF.isScalar() && Legal->blockNeedsPredication(BB))
  5766. BlockCost.first /= getReciprocalPredBlockProb();
  5767. Cost.first += BlockCost.first;
  5768. Cost.second |= BlockCost.second;
  5769. }
  5770. return Cost;
  5771. }
  5772. /// Gets Address Access SCEV after verifying that the access pattern
  5773. /// is loop invariant except the induction variable dependence.
  5774. ///
  5775. /// This SCEV can be sent to the Target in order to estimate the address
  5776. /// calculation cost.
  5777. static const SCEV *getAddressAccessSCEV(
  5778. Value *Ptr,
  5779. LoopVectorizationLegality *Legal,
  5780. PredicatedScalarEvolution &PSE,
  5781. const Loop *TheLoop) {
  5782. auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  5783. if (!Gep)
  5784. return nullptr;
  5785. // We are looking for a gep with all loop invariant indices except for one
  5786. // which should be an induction variable.
  5787. auto SE = PSE.getSE();
  5788. unsigned NumOperands = Gep->getNumOperands();
  5789. for (unsigned i = 1; i < NumOperands; ++i) {
  5790. Value *Opd = Gep->getOperand(i);
  5791. if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
  5792. !Legal->isInductionVariable(Opd))
  5793. return nullptr;
  5794. }
  5795. // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
  5796. return PSE.getSCEV(Ptr);
  5797. }
  5798. static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
  5799. return Legal->hasStride(I->getOperand(0)) ||
  5800. Legal->hasStride(I->getOperand(1));
  5801. }
  5802. InstructionCost
  5803. LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
  5804. ElementCount VF) {
  5805. assert(VF.isVector() &&
  5806. "Scalarization cost of instruction implies vectorization.");
  5807. if (VF.isScalable())
  5808. return InstructionCost::getInvalid();
  5809. Type *ValTy = getLoadStoreType(I);
  5810. auto SE = PSE.getSE();
  5811. unsigned AS = getLoadStoreAddressSpace(I);
  5812. Value *Ptr = getLoadStorePointerOperand(I);
  5813. Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
  5814. // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
  5815. // that it is being called from this specific place.
  5816. // Figure out whether the access is strided and get the stride value
  5817. // if it's known in compile time
  5818. const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
  5819. // Get the cost of the scalar memory instruction and address computation.
  5820. InstructionCost Cost =
  5821. VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
  5822. // Don't pass *I here, since it is scalar but will actually be part of a
  5823. // vectorized loop where the user of it is a vectorized instruction.
  5824. const Align Alignment = getLoadStoreAlignment(I);
  5825. Cost += VF.getKnownMinValue() *
  5826. TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
  5827. AS, TTI::TCK_RecipThroughput);
  5828. // Get the overhead of the extractelement and insertelement instructions
  5829. // we might create due to scalarization.
  5830. Cost += getScalarizationOverhead(I, VF);
  5831. // If we have a predicated load/store, it will need extra i1 extracts and
  5832. // conditional branches, but may not be executed for each vector lane. Scale
  5833. // the cost by the probability of executing the predicated block.
  5834. if (isPredicatedInst(I, VF)) {
  5835. Cost /= getReciprocalPredBlockProb();
  5836. // Add the cost of an i1 extract and a branch
  5837. auto *Vec_i1Ty =
  5838. VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
  5839. Cost += TTI.getScalarizationOverhead(
  5840. Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
  5841. /*Insert=*/false, /*Extract=*/true);
  5842. Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
  5843. if (useEmulatedMaskMemRefHack(I, VF))
  5844. // Artificially setting to a high enough value to practically disable
  5845. // vectorization with such operations.
  5846. Cost = 3000000;
  5847. }
  5848. return Cost;
  5849. }
  5850. InstructionCost
  5851. LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
  5852. ElementCount VF) {
  5853. Type *ValTy = getLoadStoreType(I);
  5854. auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
  5855. Value *Ptr = getLoadStorePointerOperand(I);
  5856. unsigned AS = getLoadStoreAddressSpace(I);
  5857. int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
  5858. enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  5859. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  5860. "Stride should be 1 or -1 for consecutive memory access");
  5861. const Align Alignment = getLoadStoreAlignment(I);
  5862. InstructionCost Cost = 0;
  5863. if (Legal->isMaskRequired(I))
  5864. Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
  5865. CostKind);
  5866. else
  5867. Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
  5868. CostKind, I);
  5869. bool Reverse = ConsecutiveStride < 0;
  5870. if (Reverse)
  5871. Cost +=
  5872. TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
  5873. return Cost;
  5874. }
  5875. InstructionCost
  5876. LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
  5877. ElementCount VF) {
  5878. assert(Legal->isUniformMemOp(*I));
  5879. Type *ValTy = getLoadStoreType(I);
  5880. auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
  5881. const Align Alignment = getLoadStoreAlignment(I);
  5882. unsigned AS = getLoadStoreAddressSpace(I);
  5883. enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  5884. if (isa<LoadInst>(I)) {
  5885. return TTI.getAddressComputationCost(ValTy) +
  5886. TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
  5887. CostKind) +
  5888. TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
  5889. }
  5890. StoreInst *SI = cast<StoreInst>(I);
  5891. bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
  5892. return TTI.getAddressComputationCost(ValTy) +
  5893. TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
  5894. CostKind) +
  5895. (isLoopInvariantStoreValue
  5896. ? 0
  5897. : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
  5898. VF.getKnownMinValue() - 1));
  5899. }
  5900. InstructionCost
  5901. LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
  5902. ElementCount VF) {
  5903. Type *ValTy = getLoadStoreType(I);
  5904. auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
  5905. const Align Alignment = getLoadStoreAlignment(I);
  5906. const Value *Ptr = getLoadStorePointerOperand(I);
  5907. return TTI.getAddressComputationCost(VectorTy) +
  5908. TTI.getGatherScatterOpCost(
  5909. I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
  5910. TargetTransformInfo::TCK_RecipThroughput, I);
  5911. }
  5912. InstructionCost
  5913. LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
  5914. ElementCount VF) {
  5915. // TODO: Once we have support for interleaving with scalable vectors
  5916. // we can calculate the cost properly here.
  5917. if (VF.isScalable())
  5918. return InstructionCost::getInvalid();
  5919. Type *ValTy = getLoadStoreType(I);
  5920. auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
  5921. unsigned AS = getLoadStoreAddressSpace(I);
  5922. auto Group = getInterleavedAccessGroup(I);
  5923. assert(Group && "Fail to get an interleaved access group.");
  5924. unsigned InterleaveFactor = Group->getFactor();
  5925. auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
  5926. // Holds the indices of existing members in the interleaved group.
  5927. SmallVector<unsigned, 4> Indices;
  5928. for (unsigned IF = 0; IF < InterleaveFactor; IF++)
  5929. if (Group->getMember(IF))
  5930. Indices.push_back(IF);
  5931. // Calculate the cost of the whole interleaved group.
  5932. bool UseMaskForGaps =
  5933. (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
  5934. (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
  5935. InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
  5936. I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
  5937. AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
  5938. if (Group->isReverse()) {
  5939. // TODO: Add support for reversed masked interleaved access.
  5940. assert(!Legal->isMaskRequired(I) &&
  5941. "Reverse masked interleaved access not supported.");
  5942. Cost +=
  5943. Group->getNumMembers() *
  5944. TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
  5945. }
  5946. return Cost;
  5947. }
  5948. Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
  5949. Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
  5950. using namespace llvm::PatternMatch;
  5951. // Early exit for no inloop reductions
  5952. if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
  5953. return None;
  5954. auto *VectorTy = cast<VectorType>(Ty);
  5955. // We are looking for a pattern of, and finding the minimal acceptable cost:
  5956. // reduce(mul(ext(A), ext(B))) or
  5957. // reduce(mul(A, B)) or
  5958. // reduce(ext(A)) or
  5959. // reduce(A).
  5960. // The basic idea is that we walk down the tree to do that, finding the root
  5961. // reduction instruction in InLoopReductionImmediateChains. From there we find
  5962. // the pattern of mul/ext and test the cost of the entire pattern vs the cost
  5963. // of the components. If the reduction cost is lower then we return it for the
  5964. // reduction instruction and 0 for the other instructions in the pattern. If
  5965. // it is not we return an invalid cost specifying the orignal cost method
  5966. // should be used.
  5967. Instruction *RetI = I;
  5968. if (match(RetI, m_ZExtOrSExt(m_Value()))) {
  5969. if (!RetI->hasOneUser())
  5970. return None;
  5971. RetI = RetI->user_back();
  5972. }
  5973. if (match(RetI, m_Mul(m_Value(), m_Value())) &&
  5974. RetI->user_back()->getOpcode() == Instruction::Add) {
  5975. if (!RetI->hasOneUser())
  5976. return None;
  5977. RetI = RetI->user_back();
  5978. }
  5979. // Test if the found instruction is a reduction, and if not return an invalid
  5980. // cost specifying the parent to use the original cost modelling.
  5981. if (!InLoopReductionImmediateChains.count(RetI))
  5982. return None;
  5983. // Find the reduction this chain is a part of and calculate the basic cost of
  5984. // the reduction on its own.
  5985. Instruction *LastChain = InLoopReductionImmediateChains[RetI];
  5986. Instruction *ReductionPhi = LastChain;
  5987. while (!isa<PHINode>(ReductionPhi))
  5988. ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
  5989. const RecurrenceDescriptor &RdxDesc =
  5990. Legal->getReductionVars().find(cast<PHINode>(ReductionPhi))->second;
  5991. InstructionCost BaseCost = TTI.getArithmeticReductionCost(
  5992. RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
  5993. // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
  5994. // normal fmul instruction to the cost of the fadd reduction.
  5995. if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
  5996. BaseCost +=
  5997. TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
  5998. // If we're using ordered reductions then we can just return the base cost
  5999. // here, since getArithmeticReductionCost calculates the full ordered
  6000. // reduction cost when FP reassociation is not allowed.
  6001. if (useOrderedReductions(RdxDesc))
  6002. return BaseCost;
  6003. // Get the operand that was not the reduction chain and match it to one of the
  6004. // patterns, returning the better cost if it is found.
  6005. Instruction *RedOp = RetI->getOperand(1) == LastChain
  6006. ? dyn_cast<Instruction>(RetI->getOperand(0))
  6007. : dyn_cast<Instruction>(RetI->getOperand(1));
  6008. VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
  6009. Instruction *Op0, *Op1;
  6010. if (RedOp &&
  6011. match(RedOp,
  6012. m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
  6013. match(Op0, m_ZExtOrSExt(m_Value())) &&
  6014. Op0->getOpcode() == Op1->getOpcode() &&
  6015. Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
  6016. !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
  6017. (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
  6018. // Matched reduce(ext(mul(ext(A), ext(B)))
  6019. // Note that the extend opcodes need to all match, or if A==B they will have
  6020. // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
  6021. // which is equally fine.
  6022. bool IsUnsigned = isa<ZExtInst>(Op0);
  6023. auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
  6024. auto *MulType = VectorType::get(Op0->getType(), VectorTy);
  6025. InstructionCost ExtCost =
  6026. TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
  6027. TTI::CastContextHint::None, CostKind, Op0);
  6028. InstructionCost MulCost =
  6029. TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
  6030. InstructionCost Ext2Cost =
  6031. TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
  6032. TTI::CastContextHint::None, CostKind, RedOp);
  6033. InstructionCost RedCost = TTI.getExtendedAddReductionCost(
  6034. /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
  6035. CostKind);
  6036. if (RedCost.isValid() &&
  6037. RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
  6038. return I == RetI ? RedCost : 0;
  6039. } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
  6040. !TheLoop->isLoopInvariant(RedOp)) {
  6041. // Matched reduce(ext(A))
  6042. bool IsUnsigned = isa<ZExtInst>(RedOp);
  6043. auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
  6044. InstructionCost RedCost = TTI.getExtendedAddReductionCost(
  6045. /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
  6046. CostKind);
  6047. InstructionCost ExtCost =
  6048. TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
  6049. TTI::CastContextHint::None, CostKind, RedOp);
  6050. if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
  6051. return I == RetI ? RedCost : 0;
  6052. } else if (RedOp &&
  6053. match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
  6054. if (match(Op0, m_ZExtOrSExt(m_Value())) &&
  6055. Op0->getOpcode() == Op1->getOpcode() &&
  6056. !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
  6057. bool IsUnsigned = isa<ZExtInst>(Op0);
  6058. Type *Op0Ty = Op0->getOperand(0)->getType();
  6059. Type *Op1Ty = Op1->getOperand(0)->getType();
  6060. Type *LargestOpTy =
  6061. Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
  6062. : Op0Ty;
  6063. auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
  6064. // Matched reduce(mul(ext(A), ext(B))), where the two ext may be of
  6065. // different sizes. We take the largest type as the ext to reduce, and add
  6066. // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
  6067. InstructionCost ExtCost0 = TTI.getCastInstrCost(
  6068. Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
  6069. TTI::CastContextHint::None, CostKind, Op0);
  6070. InstructionCost ExtCost1 = TTI.getCastInstrCost(
  6071. Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
  6072. TTI::CastContextHint::None, CostKind, Op1);
  6073. InstructionCost MulCost =
  6074. TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
  6075. InstructionCost RedCost = TTI.getExtendedAddReductionCost(
  6076. /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
  6077. CostKind);
  6078. InstructionCost ExtraExtCost = 0;
  6079. if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
  6080. Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
  6081. ExtraExtCost = TTI.getCastInstrCost(
  6082. ExtraExtOp->getOpcode(), ExtType,
  6083. VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
  6084. TTI::CastContextHint::None, CostKind, ExtraExtOp);
  6085. }
  6086. if (RedCost.isValid() &&
  6087. (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
  6088. return I == RetI ? RedCost : 0;
  6089. } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
  6090. // Matched reduce(mul())
  6091. InstructionCost MulCost =
  6092. TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
  6093. InstructionCost RedCost = TTI.getExtendedAddReductionCost(
  6094. /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
  6095. CostKind);
  6096. if (RedCost.isValid() && RedCost < MulCost + BaseCost)
  6097. return I == RetI ? RedCost : 0;
  6098. }
  6099. }
  6100. return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
  6101. }
  6102. InstructionCost
  6103. LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
  6104. ElementCount VF) {
  6105. // Calculate scalar cost only. Vectorization cost should be ready at this
  6106. // moment.
  6107. if (VF.isScalar()) {
  6108. Type *ValTy = getLoadStoreType(I);
  6109. const Align Alignment = getLoadStoreAlignment(I);
  6110. unsigned AS = getLoadStoreAddressSpace(I);
  6111. return TTI.getAddressComputationCost(ValTy) +
  6112. TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
  6113. TTI::TCK_RecipThroughput, I);
  6114. }
  6115. return getWideningCost(I, VF);
  6116. }
  6117. LoopVectorizationCostModel::VectorizationCostTy
  6118. LoopVectorizationCostModel::getInstructionCost(Instruction *I,
  6119. ElementCount VF) {
  6120. // If we know that this instruction will remain uniform, check the cost of
  6121. // the scalar version.
  6122. if (isUniformAfterVectorization(I, VF))
  6123. VF = ElementCount::getFixed(1);
  6124. if (VF.isVector() && isProfitableToScalarize(I, VF))
  6125. return VectorizationCostTy(InstsToScalarize[VF][I], false);
  6126. // Forced scalars do not have any scalarization overhead.
  6127. auto ForcedScalar = ForcedScalars.find(VF);
  6128. if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
  6129. auto InstSet = ForcedScalar->second;
  6130. if (InstSet.count(I))
  6131. return VectorizationCostTy(
  6132. (getInstructionCost(I, ElementCount::getFixed(1)).first *
  6133. VF.getKnownMinValue()),
  6134. false);
  6135. }
  6136. Type *VectorTy;
  6137. InstructionCost C = getInstructionCost(I, VF, VectorTy);
  6138. bool TypeNotScalarized = false;
  6139. if (VF.isVector() && VectorTy->isVectorTy()) {
  6140. unsigned NumParts = TTI.getNumberOfParts(VectorTy);
  6141. if (NumParts)
  6142. TypeNotScalarized = NumParts < VF.getKnownMinValue();
  6143. else
  6144. C = InstructionCost::getInvalid();
  6145. }
  6146. return VectorizationCostTy(C, TypeNotScalarized);
  6147. }
  6148. InstructionCost
  6149. LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
  6150. ElementCount VF) const {
  6151. // There is no mechanism yet to create a scalable scalarization loop,
  6152. // so this is currently Invalid.
  6153. if (VF.isScalable())
  6154. return InstructionCost::getInvalid();
  6155. if (VF.isScalar())
  6156. return 0;
  6157. InstructionCost Cost = 0;
  6158. Type *RetTy = ToVectorTy(I->getType(), VF);
  6159. if (!RetTy->isVoidTy() &&
  6160. (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
  6161. Cost += TTI.getScalarizationOverhead(
  6162. cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
  6163. false);
  6164. // Some targets keep addresses scalar.
  6165. if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
  6166. return Cost;
  6167. // Some targets support efficient element stores.
  6168. if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
  6169. return Cost;
  6170. // Collect operands to consider.
  6171. CallInst *CI = dyn_cast<CallInst>(I);
  6172. Instruction::op_range Ops = CI ? CI->args() : I->operands();
  6173. // Skip operands that do not require extraction/scalarization and do not incur
  6174. // any overhead.
  6175. SmallVector<Type *> Tys;
  6176. for (auto *V : filterExtractingOperands(Ops, VF))
  6177. Tys.push_back(MaybeVectorizeType(V->getType(), VF));
  6178. return Cost + TTI.getOperandsScalarizationOverhead(
  6179. filterExtractingOperands(Ops, VF), Tys);
  6180. }
  6181. void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
  6182. if (VF.isScalar())
  6183. return;
  6184. NumPredStores = 0;
  6185. for (BasicBlock *BB : TheLoop->blocks()) {
  6186. // For each instruction in the old loop.
  6187. for (Instruction &I : *BB) {
  6188. Value *Ptr = getLoadStorePointerOperand(&I);
  6189. if (!Ptr)
  6190. continue;
  6191. // TODO: We should generate better code and update the cost model for
  6192. // predicated uniform stores. Today they are treated as any other
  6193. // predicated store (see added test cases in
  6194. // invariant-store-vectorization.ll).
  6195. if (isa<StoreInst>(&I) && isScalarWithPredication(&I, VF))
  6196. NumPredStores++;
  6197. if (Legal->isUniformMemOp(I)) {
  6198. // TODO: Avoid replicating loads and stores instead of
  6199. // relying on instcombine to remove them.
  6200. // Load: Scalar load + broadcast
  6201. // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
  6202. InstructionCost Cost;
  6203. if (isa<StoreInst>(&I) && VF.isScalable() &&
  6204. isLegalGatherOrScatter(&I, VF)) {
  6205. Cost = getGatherScatterCost(&I, VF);
  6206. setWideningDecision(&I, VF, CM_GatherScatter, Cost);
  6207. } else {
  6208. assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
  6209. "Cannot yet scalarize uniform stores");
  6210. Cost = getUniformMemOpCost(&I, VF);
  6211. setWideningDecision(&I, VF, CM_Scalarize, Cost);
  6212. }
  6213. continue;
  6214. }
  6215. // We assume that widening is the best solution when possible.
  6216. if (memoryInstructionCanBeWidened(&I, VF)) {
  6217. InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
  6218. int ConsecutiveStride = Legal->isConsecutivePtr(
  6219. getLoadStoreType(&I), getLoadStorePointerOperand(&I));
  6220. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  6221. "Expected consecutive stride.");
  6222. InstWidening Decision =
  6223. ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
  6224. setWideningDecision(&I, VF, Decision, Cost);
  6225. continue;
  6226. }
  6227. // Choose between Interleaving, Gather/Scatter or Scalarization.
  6228. InstructionCost InterleaveCost = InstructionCost::getInvalid();
  6229. unsigned NumAccesses = 1;
  6230. if (isAccessInterleaved(&I)) {
  6231. auto Group = getInterleavedAccessGroup(&I);
  6232. assert(Group && "Fail to get an interleaved access group.");
  6233. // Make one decision for the whole group.
  6234. if (getWideningDecision(&I, VF) != CM_Unknown)
  6235. continue;
  6236. NumAccesses = Group->getNumMembers();
  6237. if (interleavedAccessCanBeWidened(&I, VF))
  6238. InterleaveCost = getInterleaveGroupCost(&I, VF);
  6239. }
  6240. InstructionCost GatherScatterCost =
  6241. isLegalGatherOrScatter(&I, VF)
  6242. ? getGatherScatterCost(&I, VF) * NumAccesses
  6243. : InstructionCost::getInvalid();
  6244. InstructionCost ScalarizationCost =
  6245. getMemInstScalarizationCost(&I, VF) * NumAccesses;
  6246. // Choose better solution for the current VF,
  6247. // write down this decision and use it during vectorization.
  6248. InstructionCost Cost;
  6249. InstWidening Decision;
  6250. if (InterleaveCost <= GatherScatterCost &&
  6251. InterleaveCost < ScalarizationCost) {
  6252. Decision = CM_Interleave;
  6253. Cost = InterleaveCost;
  6254. } else if (GatherScatterCost < ScalarizationCost) {
  6255. Decision = CM_GatherScatter;
  6256. Cost = GatherScatterCost;
  6257. } else {
  6258. Decision = CM_Scalarize;
  6259. Cost = ScalarizationCost;
  6260. }
  6261. // If the instructions belongs to an interleave group, the whole group
  6262. // receives the same decision. The whole group receives the cost, but
  6263. // the cost will actually be assigned to one instruction.
  6264. if (auto Group = getInterleavedAccessGroup(&I))
  6265. setWideningDecision(Group, VF, Decision, Cost);
  6266. else
  6267. setWideningDecision(&I, VF, Decision, Cost);
  6268. }
  6269. }
  6270. // Make sure that any load of address and any other address computation
  6271. // remains scalar unless there is gather/scatter support. This avoids
  6272. // inevitable extracts into address registers, and also has the benefit of
  6273. // activating LSR more, since that pass can't optimize vectorized
  6274. // addresses.
  6275. if (TTI.prefersVectorizedAddressing())
  6276. return;
  6277. // Start with all scalar pointer uses.
  6278. SmallPtrSet<Instruction *, 8> AddrDefs;
  6279. for (BasicBlock *BB : TheLoop->blocks())
  6280. for (Instruction &I : *BB) {
  6281. Instruction *PtrDef =
  6282. dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
  6283. if (PtrDef && TheLoop->contains(PtrDef) &&
  6284. getWideningDecision(&I, VF) != CM_GatherScatter)
  6285. AddrDefs.insert(PtrDef);
  6286. }
  6287. // Add all instructions used to generate the addresses.
  6288. SmallVector<Instruction *, 4> Worklist;
  6289. append_range(Worklist, AddrDefs);
  6290. while (!Worklist.empty()) {
  6291. Instruction *I = Worklist.pop_back_val();
  6292. for (auto &Op : I->operands())
  6293. if (auto *InstOp = dyn_cast<Instruction>(Op))
  6294. if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
  6295. AddrDefs.insert(InstOp).second)
  6296. Worklist.push_back(InstOp);
  6297. }
  6298. for (auto *I : AddrDefs) {
  6299. if (isa<LoadInst>(I)) {
  6300. // Setting the desired widening decision should ideally be handled in
  6301. // by cost functions, but since this involves the task of finding out
  6302. // if the loaded register is involved in an address computation, it is
  6303. // instead changed here when we know this is the case.
  6304. InstWidening Decision = getWideningDecision(I, VF);
  6305. if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
  6306. // Scalarize a widened load of address.
  6307. setWideningDecision(
  6308. I, VF, CM_Scalarize,
  6309. (VF.getKnownMinValue() *
  6310. getMemoryInstructionCost(I, ElementCount::getFixed(1))));
  6311. else if (auto Group = getInterleavedAccessGroup(I)) {
  6312. // Scalarize an interleave group of address loads.
  6313. for (unsigned I = 0; I < Group->getFactor(); ++I) {
  6314. if (Instruction *Member = Group->getMember(I))
  6315. setWideningDecision(
  6316. Member, VF, CM_Scalarize,
  6317. (VF.getKnownMinValue() *
  6318. getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
  6319. }
  6320. }
  6321. } else
  6322. // Make sure I gets scalarized and a cost estimate without
  6323. // scalarization overhead.
  6324. ForcedScalars[VF].insert(I);
  6325. }
  6326. }
  6327. InstructionCost
  6328. LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
  6329. Type *&VectorTy) {
  6330. Type *RetTy = I->getType();
  6331. if (canTruncateToMinimalBitwidth(I, VF))
  6332. RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
  6333. auto SE = PSE.getSE();
  6334. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  6335. auto hasSingleCopyAfterVectorization = [this](Instruction *I,
  6336. ElementCount VF) -> bool {
  6337. if (VF.isScalar())
  6338. return true;
  6339. auto Scalarized = InstsToScalarize.find(VF);
  6340. assert(Scalarized != InstsToScalarize.end() &&
  6341. "VF not yet analyzed for scalarization profitability");
  6342. return !Scalarized->second.count(I) &&
  6343. llvm::all_of(I->users(), [&](User *U) {
  6344. auto *UI = cast<Instruction>(U);
  6345. return !Scalarized->second.count(UI);
  6346. });
  6347. };
  6348. (void) hasSingleCopyAfterVectorization;
  6349. if (isScalarAfterVectorization(I, VF)) {
  6350. // With the exception of GEPs and PHIs, after scalarization there should
  6351. // only be one copy of the instruction generated in the loop. This is
  6352. // because the VF is either 1, or any instructions that need scalarizing
  6353. // have already been dealt with by the the time we get here. As a result,
  6354. // it means we don't have to multiply the instruction cost by VF.
  6355. assert(I->getOpcode() == Instruction::GetElementPtr ||
  6356. I->getOpcode() == Instruction::PHI ||
  6357. (I->getOpcode() == Instruction::BitCast &&
  6358. I->getType()->isPointerTy()) ||
  6359. hasSingleCopyAfterVectorization(I, VF));
  6360. VectorTy = RetTy;
  6361. } else
  6362. VectorTy = ToVectorTy(RetTy, VF);
  6363. // TODO: We need to estimate the cost of intrinsic calls.
  6364. switch (I->getOpcode()) {
  6365. case Instruction::GetElementPtr:
  6366. // We mark this instruction as zero-cost because the cost of GEPs in
  6367. // vectorized code depends on whether the corresponding memory instruction
  6368. // is scalarized or not. Therefore, we handle GEPs with the memory
  6369. // instruction cost.
  6370. return 0;
  6371. case Instruction::Br: {
  6372. // In cases of scalarized and predicated instructions, there will be VF
  6373. // predicated blocks in the vectorized loop. Each branch around these
  6374. // blocks requires also an extract of its vector compare i1 element.
  6375. bool ScalarPredicatedBB = false;
  6376. BranchInst *BI = cast<BranchInst>(I);
  6377. if (VF.isVector() && BI->isConditional() &&
  6378. (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
  6379. PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
  6380. ScalarPredicatedBB = true;
  6381. if (ScalarPredicatedBB) {
  6382. // Not possible to scalarize scalable vector with predicated instructions.
  6383. if (VF.isScalable())
  6384. return InstructionCost::getInvalid();
  6385. // Return cost for branches around scalarized and predicated blocks.
  6386. auto *Vec_i1Ty =
  6387. VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
  6388. return (
  6389. TTI.getScalarizationOverhead(
  6390. Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
  6391. (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
  6392. } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
  6393. // The back-edge branch will remain, as will all scalar branches.
  6394. return TTI.getCFInstrCost(Instruction::Br, CostKind);
  6395. else
  6396. // This branch will be eliminated by if-conversion.
  6397. return 0;
  6398. // Note: We currently assume zero cost for an unconditional branch inside
  6399. // a predicated block since it will become a fall-through, although we
  6400. // may decide in the future to call TTI for all branches.
  6401. }
  6402. case Instruction::PHI: {
  6403. auto *Phi = cast<PHINode>(I);
  6404. // First-order recurrences are replaced by vector shuffles inside the loop.
  6405. // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
  6406. if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
  6407. return TTI.getShuffleCost(
  6408. TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
  6409. None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
  6410. // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
  6411. // converted into select instructions. We require N - 1 selects per phi
  6412. // node, where N is the number of incoming values.
  6413. if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
  6414. return (Phi->getNumIncomingValues() - 1) *
  6415. TTI.getCmpSelInstrCost(
  6416. Instruction::Select, ToVectorTy(Phi->getType(), VF),
  6417. ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
  6418. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  6419. return TTI.getCFInstrCost(Instruction::PHI, CostKind);
  6420. }
  6421. case Instruction::UDiv:
  6422. case Instruction::SDiv:
  6423. case Instruction::URem:
  6424. case Instruction::SRem:
  6425. // If we have a predicated instruction, it may not be executed for each
  6426. // vector lane. Get the scalarization cost and scale this amount by the
  6427. // probability of executing the predicated block. If the instruction is not
  6428. // predicated, we fall through to the next case.
  6429. if (VF.isVector() && isScalarWithPredication(I, VF)) {
  6430. InstructionCost Cost = 0;
  6431. // These instructions have a non-void type, so account for the phi nodes
  6432. // that we will create. This cost is likely to be zero. The phi node
  6433. // cost, if any, should be scaled by the block probability because it
  6434. // models a copy at the end of each predicated block.
  6435. Cost += VF.getKnownMinValue() *
  6436. TTI.getCFInstrCost(Instruction::PHI, CostKind);
  6437. // The cost of the non-predicated instruction.
  6438. Cost += VF.getKnownMinValue() *
  6439. TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
  6440. // The cost of insertelement and extractelement instructions needed for
  6441. // scalarization.
  6442. Cost += getScalarizationOverhead(I, VF);
  6443. // Scale the cost by the probability of executing the predicated blocks.
  6444. // This assumes the predicated block for each vector lane is equally
  6445. // likely.
  6446. return Cost / getReciprocalPredBlockProb();
  6447. }
  6448. LLVM_FALLTHROUGH;
  6449. case Instruction::Add:
  6450. case Instruction::FAdd:
  6451. case Instruction::Sub:
  6452. case Instruction::FSub:
  6453. case Instruction::Mul:
  6454. case Instruction::FMul:
  6455. case Instruction::FDiv:
  6456. case Instruction::FRem:
  6457. case Instruction::Shl:
  6458. case Instruction::LShr:
  6459. case Instruction::AShr:
  6460. case Instruction::And:
  6461. case Instruction::Or:
  6462. case Instruction::Xor: {
  6463. // Since we will replace the stride by 1 the multiplication should go away.
  6464. if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
  6465. return 0;
  6466. // Detect reduction patterns
  6467. if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
  6468. return *RedCost;
  6469. // Certain instructions can be cheaper to vectorize if they have a constant
  6470. // second vector operand. One example of this are shifts on x86.
  6471. Value *Op2 = I->getOperand(1);
  6472. TargetTransformInfo::OperandValueProperties Op2VP;
  6473. TargetTransformInfo::OperandValueKind Op2VK =
  6474. TTI.getOperandInfo(Op2, Op2VP);
  6475. if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
  6476. Op2VK = TargetTransformInfo::OK_UniformValue;
  6477. SmallVector<const Value *, 4> Operands(I->operand_values());
  6478. return TTI.getArithmeticInstrCost(
  6479. I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
  6480. Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
  6481. }
  6482. case Instruction::FNeg: {
  6483. return TTI.getArithmeticInstrCost(
  6484. I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
  6485. TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
  6486. TargetTransformInfo::OP_None, I->getOperand(0), I);
  6487. }
  6488. case Instruction::Select: {
  6489. SelectInst *SI = cast<SelectInst>(I);
  6490. const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
  6491. bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
  6492. const Value *Op0, *Op1;
  6493. using namespace llvm::PatternMatch;
  6494. if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
  6495. match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
  6496. // select x, y, false --> x & y
  6497. // select x, true, y --> x | y
  6498. TTI::OperandValueProperties Op1VP = TTI::OP_None;
  6499. TTI::OperandValueProperties Op2VP = TTI::OP_None;
  6500. TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
  6501. TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
  6502. assert(Op0->getType()->getScalarSizeInBits() == 1 &&
  6503. Op1->getType()->getScalarSizeInBits() == 1);
  6504. SmallVector<const Value *, 2> Operands{Op0, Op1};
  6505. return TTI.getArithmeticInstrCost(
  6506. match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
  6507. CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
  6508. }
  6509. Type *CondTy = SI->getCondition()->getType();
  6510. if (!ScalarCond)
  6511. CondTy = VectorType::get(CondTy, VF);
  6512. CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
  6513. if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
  6514. Pred = Cmp->getPredicate();
  6515. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
  6516. CostKind, I);
  6517. }
  6518. case Instruction::ICmp:
  6519. case Instruction::FCmp: {
  6520. Type *ValTy = I->getOperand(0)->getType();
  6521. Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
  6522. if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
  6523. ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
  6524. VectorTy = ToVectorTy(ValTy, VF);
  6525. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
  6526. cast<CmpInst>(I)->getPredicate(), CostKind,
  6527. I);
  6528. }
  6529. case Instruction::Store:
  6530. case Instruction::Load: {
  6531. ElementCount Width = VF;
  6532. if (Width.isVector()) {
  6533. InstWidening Decision = getWideningDecision(I, Width);
  6534. assert(Decision != CM_Unknown &&
  6535. "CM decision should be taken at this point");
  6536. if (Decision == CM_Scalarize)
  6537. Width = ElementCount::getFixed(1);
  6538. }
  6539. VectorTy = ToVectorTy(getLoadStoreType(I), Width);
  6540. return getMemoryInstructionCost(I, VF);
  6541. }
  6542. case Instruction::BitCast:
  6543. if (I->getType()->isPointerTy())
  6544. return 0;
  6545. LLVM_FALLTHROUGH;
  6546. case Instruction::ZExt:
  6547. case Instruction::SExt:
  6548. case Instruction::FPToUI:
  6549. case Instruction::FPToSI:
  6550. case Instruction::FPExt:
  6551. case Instruction::PtrToInt:
  6552. case Instruction::IntToPtr:
  6553. case Instruction::SIToFP:
  6554. case Instruction::UIToFP:
  6555. case Instruction::Trunc:
  6556. case Instruction::FPTrunc: {
  6557. // Computes the CastContextHint from a Load/Store instruction.
  6558. auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
  6559. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  6560. "Expected a load or a store!");
  6561. if (VF.isScalar() || !TheLoop->contains(I))
  6562. return TTI::CastContextHint::Normal;
  6563. switch (getWideningDecision(I, VF)) {
  6564. case LoopVectorizationCostModel::CM_GatherScatter:
  6565. return TTI::CastContextHint::GatherScatter;
  6566. case LoopVectorizationCostModel::CM_Interleave:
  6567. return TTI::CastContextHint::Interleave;
  6568. case LoopVectorizationCostModel::CM_Scalarize:
  6569. case LoopVectorizationCostModel::CM_Widen:
  6570. return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
  6571. : TTI::CastContextHint::Normal;
  6572. case LoopVectorizationCostModel::CM_Widen_Reverse:
  6573. return TTI::CastContextHint::Reversed;
  6574. case LoopVectorizationCostModel::CM_Unknown:
  6575. llvm_unreachable("Instr did not go through cost modelling?");
  6576. }
  6577. llvm_unreachable("Unhandled case!");
  6578. };
  6579. unsigned Opcode = I->getOpcode();
  6580. TTI::CastContextHint CCH = TTI::CastContextHint::None;
  6581. // For Trunc, the context is the only user, which must be a StoreInst.
  6582. if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
  6583. if (I->hasOneUse())
  6584. if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
  6585. CCH = ComputeCCH(Store);
  6586. }
  6587. // For Z/Sext, the context is the operand, which must be a LoadInst.
  6588. else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
  6589. Opcode == Instruction::FPExt) {
  6590. if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
  6591. CCH = ComputeCCH(Load);
  6592. }
  6593. // We optimize the truncation of induction variables having constant
  6594. // integer steps. The cost of these truncations is the same as the scalar
  6595. // operation.
  6596. if (isOptimizableIVTruncate(I, VF)) {
  6597. auto *Trunc = cast<TruncInst>(I);
  6598. return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
  6599. Trunc->getSrcTy(), CCH, CostKind, Trunc);
  6600. }
  6601. // Detect reduction patterns
  6602. if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
  6603. return *RedCost;
  6604. Type *SrcScalarTy = I->getOperand(0)->getType();
  6605. Type *SrcVecTy =
  6606. VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
  6607. if (canTruncateToMinimalBitwidth(I, VF)) {
  6608. // This cast is going to be shrunk. This may remove the cast or it might
  6609. // turn it into slightly different cast. For example, if MinBW == 16,
  6610. // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
  6611. //
  6612. // Calculate the modified src and dest types.
  6613. Type *MinVecTy = VectorTy;
  6614. if (Opcode == Instruction::Trunc) {
  6615. SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
  6616. VectorTy =
  6617. largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  6618. } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
  6619. SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
  6620. VectorTy =
  6621. smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  6622. }
  6623. }
  6624. return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
  6625. }
  6626. case Instruction::Call: {
  6627. if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
  6628. if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
  6629. return *RedCost;
  6630. bool NeedToScalarize;
  6631. CallInst *CI = cast<CallInst>(I);
  6632. InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
  6633. if (getVectorIntrinsicIDForCall(CI, TLI)) {
  6634. InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
  6635. return std::min(CallCost, IntrinsicCost);
  6636. }
  6637. return CallCost;
  6638. }
  6639. case Instruction::ExtractValue:
  6640. return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
  6641. case Instruction::Alloca:
  6642. // We cannot easily widen alloca to a scalable alloca, as
  6643. // the result would need to be a vector of pointers.
  6644. if (VF.isScalable())
  6645. return InstructionCost::getInvalid();
  6646. LLVM_FALLTHROUGH;
  6647. default:
  6648. // This opcode is unknown. Assume that it is the same as 'mul'.
  6649. return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
  6650. } // end of switch.
  6651. }
  6652. char LoopVectorize::ID = 0;
  6653. static const char lv_name[] = "Loop Vectorization";
  6654. INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
  6655. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  6656. INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
  6657. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  6658. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  6659. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  6660. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  6661. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  6662. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  6663. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  6664. INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
  6665. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  6666. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  6667. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  6668. INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
  6669. INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
  6670. namespace llvm {
  6671. Pass *createLoopVectorizePass() { return new LoopVectorize(); }
  6672. Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
  6673. bool VectorizeOnlyWhenForced) {
  6674. return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
  6675. }
  6676. } // end namespace llvm
  6677. bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
  6678. // Check if the pointer operand of a load or store instruction is
  6679. // consecutive.
  6680. if (auto *Ptr = getLoadStorePointerOperand(Inst))
  6681. return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
  6682. return false;
  6683. }
  6684. void LoopVectorizationCostModel::collectValuesToIgnore() {
  6685. // Ignore ephemeral values.
  6686. CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
  6687. // Ignore type-promoting instructions we identified during reduction
  6688. // detection.
  6689. for (auto &Reduction : Legal->getReductionVars()) {
  6690. const RecurrenceDescriptor &RedDes = Reduction.second;
  6691. const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
  6692. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  6693. }
  6694. // Ignore type-casting instructions we identified during induction
  6695. // detection.
  6696. for (auto &Induction : Legal->getInductionVars()) {
  6697. const InductionDescriptor &IndDes = Induction.second;
  6698. const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
  6699. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  6700. }
  6701. }
  6702. void LoopVectorizationCostModel::collectInLoopReductions() {
  6703. for (auto &Reduction : Legal->getReductionVars()) {
  6704. PHINode *Phi = Reduction.first;
  6705. const RecurrenceDescriptor &RdxDesc = Reduction.second;
  6706. // We don't collect reductions that are type promoted (yet).
  6707. if (RdxDesc.getRecurrenceType() != Phi->getType())
  6708. continue;
  6709. // If the target would prefer this reduction to happen "in-loop", then we
  6710. // want to record it as such.
  6711. unsigned Opcode = RdxDesc.getOpcode();
  6712. if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
  6713. !TTI.preferInLoopReduction(Opcode, Phi->getType(),
  6714. TargetTransformInfo::ReductionFlags()))
  6715. continue;
  6716. // Check that we can correctly put the reductions into the loop, by
  6717. // finding the chain of operations that leads from the phi to the loop
  6718. // exit value.
  6719. SmallVector<Instruction *, 4> ReductionOperations =
  6720. RdxDesc.getReductionOpChain(Phi, TheLoop);
  6721. bool InLoop = !ReductionOperations.empty();
  6722. if (InLoop) {
  6723. InLoopReductionChains[Phi] = ReductionOperations;
  6724. // Add the elements to InLoopReductionImmediateChains for cost modelling.
  6725. Instruction *LastChain = Phi;
  6726. for (auto *I : ReductionOperations) {
  6727. InLoopReductionImmediateChains[I] = LastChain;
  6728. LastChain = I;
  6729. }
  6730. }
  6731. LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
  6732. << " reduction for phi: " << *Phi << "\n");
  6733. }
  6734. }
  6735. // TODO: we could return a pair of values that specify the max VF and
  6736. // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
  6737. // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
  6738. // doesn't have a cost model that can choose which plan to execute if
  6739. // more than one is generated.
  6740. static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
  6741. LoopVectorizationCostModel &CM) {
  6742. unsigned WidestType;
  6743. std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
  6744. return WidestVectorRegBits / WidestType;
  6745. }
  6746. VectorizationFactor
  6747. LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
  6748. assert(!UserVF.isScalable() && "scalable vectors not yet supported");
  6749. ElementCount VF = UserVF;
  6750. // Outer loop handling: They may require CFG and instruction level
  6751. // transformations before even evaluating whether vectorization is profitable.
  6752. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  6753. // the vectorization pipeline.
  6754. if (!OrigLoop->isInnermost()) {
  6755. // If the user doesn't provide a vectorization factor, determine a
  6756. // reasonable one.
  6757. if (UserVF.isZero()) {
  6758. VF = ElementCount::getFixed(determineVPlanVF(
  6759. TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
  6760. .getFixedSize(),
  6761. CM));
  6762. LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
  6763. // Make sure we have a VF > 1 for stress testing.
  6764. if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
  6765. LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
  6766. << "overriding computed VF.\n");
  6767. VF = ElementCount::getFixed(4);
  6768. }
  6769. }
  6770. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  6771. assert(isPowerOf2_32(VF.getKnownMinValue()) &&
  6772. "VF needs to be a power of two");
  6773. LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
  6774. << "VF " << VF << " to build VPlans.\n");
  6775. buildVPlans(VF, VF);
  6776. // For VPlan build stress testing, we bail out after VPlan construction.
  6777. if (VPlanBuildStressTest)
  6778. return VectorizationFactor::Disabled();
  6779. return {VF, 0 /*Cost*/};
  6780. }
  6781. LLVM_DEBUG(
  6782. dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
  6783. "VPlan-native path.\n");
  6784. return VectorizationFactor::Disabled();
  6785. }
  6786. Optional<VectorizationFactor>
  6787. LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
  6788. assert(OrigLoop->isInnermost() && "Inner loop expected.");
  6789. FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
  6790. if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
  6791. return None;
  6792. // Invalidate interleave groups if all blocks of loop will be predicated.
  6793. if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
  6794. !useMaskedInterleavedAccesses(*TTI)) {
  6795. LLVM_DEBUG(
  6796. dbgs()
  6797. << "LV: Invalidate all interleaved groups due to fold-tail by masking "
  6798. "which requires masked-interleaved support.\n");
  6799. if (CM.InterleaveInfo.invalidateGroups())
  6800. // Invalidating interleave groups also requires invalidating all decisions
  6801. // based on them, which includes widening decisions and uniform and scalar
  6802. // values.
  6803. CM.invalidateCostModelingDecisions();
  6804. }
  6805. ElementCount MaxUserVF =
  6806. UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
  6807. bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
  6808. if (!UserVF.isZero() && UserVFIsLegal) {
  6809. assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
  6810. "VF needs to be a power of two");
  6811. // Collect the instructions (and their associated costs) that will be more
  6812. // profitable to scalarize.
  6813. if (CM.selectUserVectorizationFactor(UserVF)) {
  6814. LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
  6815. CM.collectInLoopReductions();
  6816. buildVPlansWithVPRecipes(UserVF, UserVF);
  6817. LLVM_DEBUG(printPlans(dbgs()));
  6818. return {{UserVF, 0}};
  6819. } else
  6820. reportVectorizationInfo("UserVF ignored because of invalid costs.",
  6821. "InvalidCost", ORE, OrigLoop);
  6822. }
  6823. // Populate the set of Vectorization Factor Candidates.
  6824. ElementCountSet VFCandidates;
  6825. for (auto VF = ElementCount::getFixed(1);
  6826. ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
  6827. VFCandidates.insert(VF);
  6828. for (auto VF = ElementCount::getScalable(1);
  6829. ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
  6830. VFCandidates.insert(VF);
  6831. for (const auto &VF : VFCandidates) {
  6832. // Collect Uniform and Scalar instructions after vectorization with VF.
  6833. CM.collectUniformsAndScalars(VF);
  6834. // Collect the instructions (and their associated costs) that will be more
  6835. // profitable to scalarize.
  6836. if (VF.isVector())
  6837. CM.collectInstsToScalarize(VF);
  6838. }
  6839. CM.collectInLoopReductions();
  6840. buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
  6841. buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
  6842. LLVM_DEBUG(printPlans(dbgs()));
  6843. if (!MaxFactors.hasVector())
  6844. return VectorizationFactor::Disabled();
  6845. // Select the optimal vectorization factor.
  6846. auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
  6847. // Check if it is profitable to vectorize with runtime checks.
  6848. unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
  6849. if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
  6850. bool PragmaThresholdReached =
  6851. NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
  6852. bool ThresholdReached =
  6853. NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
  6854. if ((ThresholdReached && !Hints.allowReordering()) ||
  6855. PragmaThresholdReached) {
  6856. ORE->emit([&]() {
  6857. return OptimizationRemarkAnalysisAliasing(
  6858. DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
  6859. OrigLoop->getHeader())
  6860. << "loop not vectorized: cannot prove it is safe to reorder "
  6861. "memory operations";
  6862. });
  6863. LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
  6864. Hints.emitRemarkWithHints();
  6865. return VectorizationFactor::Disabled();
  6866. }
  6867. }
  6868. return SelectedVF;
  6869. }
  6870. VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
  6871. assert(count_if(VPlans,
  6872. [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
  6873. 1 &&
  6874. "Best VF has not a single VPlan.");
  6875. for (const VPlanPtr &Plan : VPlans) {
  6876. if (Plan->hasVF(VF))
  6877. return *Plan.get();
  6878. }
  6879. llvm_unreachable("No plan found!");
  6880. }
  6881. static void AddRuntimeUnrollDisableMetaData(Loop *L) {
  6882. SmallVector<Metadata *, 4> MDs;
  6883. // Reserve first location for self reference to the LoopID metadata node.
  6884. MDs.push_back(nullptr);
  6885. bool IsUnrollMetadata = false;
  6886. MDNode *LoopID = L->getLoopID();
  6887. if (LoopID) {
  6888. // First find existing loop unrolling disable metadata.
  6889. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  6890. auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  6891. if (MD) {
  6892. const auto *S = dyn_cast<MDString>(MD->getOperand(0));
  6893. IsUnrollMetadata =
  6894. S && S->getString().startswith("llvm.loop.unroll.disable");
  6895. }
  6896. MDs.push_back(LoopID->getOperand(i));
  6897. }
  6898. }
  6899. if (!IsUnrollMetadata) {
  6900. // Add runtime unroll disable metadata.
  6901. LLVMContext &Context = L->getHeader()->getContext();
  6902. SmallVector<Metadata *, 1> DisableOperands;
  6903. DisableOperands.push_back(
  6904. MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
  6905. MDNode *DisableNode = MDNode::get(Context, DisableOperands);
  6906. MDs.push_back(DisableNode);
  6907. MDNode *NewLoopID = MDNode::get(Context, MDs);
  6908. // Set operand 0 to refer to the loop id itself.
  6909. NewLoopID->replaceOperandWith(0, NewLoopID);
  6910. L->setLoopID(NewLoopID);
  6911. }
  6912. }
  6913. void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
  6914. VPlan &BestVPlan,
  6915. InnerLoopVectorizer &ILV,
  6916. DominatorTree *DT) {
  6917. LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
  6918. << '\n');
  6919. // Perform the actual loop transformation.
  6920. // 1. Create a new empty loop. Unlink the old loop and connect the new one.
  6921. VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
  6922. Value *CanonicalIVStartValue;
  6923. std::tie(State.CFG.PrevBB, CanonicalIVStartValue) =
  6924. ILV.createVectorizedLoopSkeleton();
  6925. ILV.collectPoisonGeneratingRecipes(State);
  6926. ILV.printDebugTracesAtStart();
  6927. //===------------------------------------------------===//
  6928. //
  6929. // Notice: any optimization or new instruction that go
  6930. // into the code below should also be implemented in
  6931. // the cost-model.
  6932. //
  6933. //===------------------------------------------------===//
  6934. // 2. Copy and widen instructions from the old loop into the new loop.
  6935. BestVPlan.prepareToExecute(ILV.getOrCreateTripCount(nullptr),
  6936. ILV.getOrCreateVectorTripCount(nullptr),
  6937. CanonicalIVStartValue, State);
  6938. BestVPlan.execute(&State);
  6939. // Keep all loop hints from the original loop on the vector loop (we'll
  6940. // replace the vectorizer-specific hints below).
  6941. MDNode *OrigLoopID = OrigLoop->getLoopID();
  6942. Optional<MDNode *> VectorizedLoopID =
  6943. makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
  6944. LLVMLoopVectorizeFollowupVectorized});
  6945. Loop *L = LI->getLoopFor(State.CFG.PrevBB);
  6946. if (VectorizedLoopID.hasValue())
  6947. L->setLoopID(VectorizedLoopID.getValue());
  6948. else {
  6949. // Keep all loop hints from the original loop on the vector loop (we'll
  6950. // replace the vectorizer-specific hints below).
  6951. if (MDNode *LID = OrigLoop->getLoopID())
  6952. L->setLoopID(LID);
  6953. LoopVectorizeHints Hints(L, true, *ORE);
  6954. Hints.setAlreadyVectorized();
  6955. }
  6956. // Disable runtime unrolling when vectorizing the epilogue loop.
  6957. if (CanonicalIVStartValue)
  6958. AddRuntimeUnrollDisableMetaData(L);
  6959. // 3. Fix the vectorized code: take care of header phi's, live-outs,
  6960. // predication, updating analyses.
  6961. ILV.fixVectorizedLoop(State);
  6962. ILV.printDebugTracesAtEnd();
  6963. }
  6964. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  6965. void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
  6966. for (const auto &Plan : VPlans)
  6967. if (PrintVPlansInDotFormat)
  6968. Plan->printDOT(O);
  6969. else
  6970. Plan->print(O);
  6971. }
  6972. #endif
  6973. void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
  6974. SmallPtrSetImpl<Instruction *> &DeadInstructions) {
  6975. // We create new control-flow for the vectorized loop, so the original exit
  6976. // conditions will be dead after vectorization if it's only used by the
  6977. // terminator
  6978. SmallVector<BasicBlock*> ExitingBlocks;
  6979. OrigLoop->getExitingBlocks(ExitingBlocks);
  6980. for (auto *BB : ExitingBlocks) {
  6981. auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
  6982. if (!Cmp || !Cmp->hasOneUse())
  6983. continue;
  6984. // TODO: we should introduce a getUniqueExitingBlocks on Loop
  6985. if (!DeadInstructions.insert(Cmp).second)
  6986. continue;
  6987. // The operands of the icmp is often a dead trunc, used by IndUpdate.
  6988. // TODO: can recurse through operands in general
  6989. for (Value *Op : Cmp->operands()) {
  6990. if (isa<TruncInst>(Op) && Op->hasOneUse())
  6991. DeadInstructions.insert(cast<Instruction>(Op));
  6992. }
  6993. }
  6994. // We create new "steps" for induction variable updates to which the original
  6995. // induction variables map. An original update instruction will be dead if
  6996. // all its users except the induction variable are dead.
  6997. auto *Latch = OrigLoop->getLoopLatch();
  6998. for (auto &Induction : Legal->getInductionVars()) {
  6999. PHINode *Ind = Induction.first;
  7000. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  7001. // If the tail is to be folded by masking, the primary induction variable,
  7002. // if exists, isn't dead: it will be used for masking. Don't kill it.
  7003. if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
  7004. continue;
  7005. if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  7006. return U == Ind || DeadInstructions.count(cast<Instruction>(U));
  7007. }))
  7008. DeadInstructions.insert(IndUpdate);
  7009. }
  7010. }
  7011. Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
  7012. //===--------------------------------------------------------------------===//
  7013. // EpilogueVectorizerMainLoop
  7014. //===--------------------------------------------------------------------===//
  7015. /// This function is partially responsible for generating the control flow
  7016. /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
  7017. std::pair<BasicBlock *, Value *>
  7018. EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
  7019. MDNode *OrigLoopID = OrigLoop->getLoopID();
  7020. Loop *Lp = createVectorLoopSkeleton("");
  7021. // Generate the code to check the minimum iteration count of the vector
  7022. // epilogue (see below).
  7023. EPI.EpilogueIterationCountCheck =
  7024. emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
  7025. EPI.EpilogueIterationCountCheck->setName("iter.check");
  7026. // Generate the code to check any assumptions that we've made for SCEV
  7027. // expressions.
  7028. EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
  7029. // Generate the code that checks at runtime if arrays overlap. We put the
  7030. // checks into a separate block to make the more common case of few elements
  7031. // faster.
  7032. EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
  7033. // Generate the iteration count check for the main loop, *after* the check
  7034. // for the epilogue loop, so that the path-length is shorter for the case
  7035. // that goes directly through the vector epilogue. The longer-path length for
  7036. // the main loop is compensated for, by the gain from vectorizing the larger
  7037. // trip count. Note: the branch will get updated later on when we vectorize
  7038. // the epilogue.
  7039. EPI.MainLoopIterationCountCheck =
  7040. emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
  7041. // Generate the induction variable.
  7042. Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
  7043. EPI.VectorTripCount = CountRoundDown;
  7044. createHeaderBranch(Lp);
  7045. // Skip induction resume value creation here because they will be created in
  7046. // the second pass. If we created them here, they wouldn't be used anyway,
  7047. // because the vplan in the second pass still contains the inductions from the
  7048. // original loop.
  7049. return {completeLoopSkeleton(Lp, OrigLoopID), nullptr};
  7050. }
  7051. void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
  7052. LLVM_DEBUG({
  7053. dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
  7054. << "Main Loop VF:" << EPI.MainLoopVF
  7055. << ", Main Loop UF:" << EPI.MainLoopUF
  7056. << ", Epilogue Loop VF:" << EPI.EpilogueVF
  7057. << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
  7058. });
  7059. }
  7060. void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
  7061. DEBUG_WITH_TYPE(VerboseDebug, {
  7062. dbgs() << "intermediate fn:\n"
  7063. << *OrigLoop->getHeader()->getParent() << "\n";
  7064. });
  7065. }
  7066. BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
  7067. Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
  7068. assert(L && "Expected valid Loop.");
  7069. assert(Bypass && "Expected valid bypass basic block.");
  7070. ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
  7071. unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
  7072. Value *Count = getOrCreateTripCount(L);
  7073. // Reuse existing vector loop preheader for TC checks.
  7074. // Note that new preheader block is generated for vector loop.
  7075. BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
  7076. IRBuilder<> Builder(TCCheckBlock->getTerminator());
  7077. // Generate code to check if the loop's trip count is less than VF * UF of the
  7078. // main vector loop.
  7079. auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
  7080. ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
  7081. Value *CheckMinIters = Builder.CreateICmp(
  7082. P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
  7083. "min.iters.check");
  7084. if (!ForEpilogue)
  7085. TCCheckBlock->setName("vector.main.loop.iter.check");
  7086. // Create new preheader for vector loop.
  7087. LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
  7088. DT, LI, nullptr, "vector.ph");
  7089. if (ForEpilogue) {
  7090. assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
  7091. DT->getNode(Bypass)->getIDom()) &&
  7092. "TC check is expected to dominate Bypass");
  7093. // Update dominator for Bypass & LoopExit.
  7094. DT->changeImmediateDominator(Bypass, TCCheckBlock);
  7095. if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
  7096. // For loops with multiple exits, there's no edge from the middle block
  7097. // to exit blocks (as the epilogue must run) and thus no need to update
  7098. // the immediate dominator of the exit blocks.
  7099. DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
  7100. LoopBypassBlocks.push_back(TCCheckBlock);
  7101. // Save the trip count so we don't have to regenerate it in the
  7102. // vec.epilog.iter.check. This is safe to do because the trip count
  7103. // generated here dominates the vector epilog iter check.
  7104. EPI.TripCount = Count;
  7105. }
  7106. ReplaceInstWithInst(
  7107. TCCheckBlock->getTerminator(),
  7108. BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
  7109. return TCCheckBlock;
  7110. }
  7111. //===--------------------------------------------------------------------===//
  7112. // EpilogueVectorizerEpilogueLoop
  7113. //===--------------------------------------------------------------------===//
  7114. /// This function is partially responsible for generating the control flow
  7115. /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
  7116. std::pair<BasicBlock *, Value *>
  7117. EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
  7118. MDNode *OrigLoopID = OrigLoop->getLoopID();
  7119. Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
  7120. // Now, compare the remaining count and if there aren't enough iterations to
  7121. // execute the vectorized epilogue skip to the scalar part.
  7122. BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
  7123. VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
  7124. LoopVectorPreHeader =
  7125. SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
  7126. LI, nullptr, "vec.epilog.ph");
  7127. emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
  7128. VecEpilogueIterationCountCheck);
  7129. // Adjust the control flow taking the state info from the main loop
  7130. // vectorization into account.
  7131. assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
  7132. "expected this to be saved from the previous pass.");
  7133. EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
  7134. VecEpilogueIterationCountCheck, LoopVectorPreHeader);
  7135. DT->changeImmediateDominator(LoopVectorPreHeader,
  7136. EPI.MainLoopIterationCountCheck);
  7137. EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
  7138. VecEpilogueIterationCountCheck, LoopScalarPreHeader);
  7139. if (EPI.SCEVSafetyCheck)
  7140. EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
  7141. VecEpilogueIterationCountCheck, LoopScalarPreHeader);
  7142. if (EPI.MemSafetyCheck)
  7143. EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
  7144. VecEpilogueIterationCountCheck, LoopScalarPreHeader);
  7145. DT->changeImmediateDominator(
  7146. VecEpilogueIterationCountCheck,
  7147. VecEpilogueIterationCountCheck->getSinglePredecessor());
  7148. DT->changeImmediateDominator(LoopScalarPreHeader,
  7149. EPI.EpilogueIterationCountCheck);
  7150. if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
  7151. // If there is an epilogue which must run, there's no edge from the
  7152. // middle block to exit blocks and thus no need to update the immediate
  7153. // dominator of the exit blocks.
  7154. DT->changeImmediateDominator(LoopExitBlock,
  7155. EPI.EpilogueIterationCountCheck);
  7156. // Keep track of bypass blocks, as they feed start values to the induction
  7157. // phis in the scalar loop preheader.
  7158. if (EPI.SCEVSafetyCheck)
  7159. LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
  7160. if (EPI.MemSafetyCheck)
  7161. LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
  7162. LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
  7163. // The vec.epilog.iter.check block may contain Phi nodes from reductions which
  7164. // merge control-flow from the latch block and the middle block. Update the
  7165. // incoming values here and move the Phi into the preheader.
  7166. SmallVector<PHINode *, 4> PhisInBlock;
  7167. for (PHINode &Phi : VecEpilogueIterationCountCheck->phis())
  7168. PhisInBlock.push_back(&Phi);
  7169. for (PHINode *Phi : PhisInBlock) {
  7170. Phi->replaceIncomingBlockWith(
  7171. VecEpilogueIterationCountCheck->getSinglePredecessor(),
  7172. VecEpilogueIterationCountCheck);
  7173. Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
  7174. if (EPI.SCEVSafetyCheck)
  7175. Phi->removeIncomingValue(EPI.SCEVSafetyCheck);
  7176. if (EPI.MemSafetyCheck)
  7177. Phi->removeIncomingValue(EPI.MemSafetyCheck);
  7178. Phi->moveBefore(LoopVectorPreHeader->getFirstNonPHI());
  7179. }
  7180. // Generate a resume induction for the vector epilogue and put it in the
  7181. // vector epilogue preheader
  7182. Type *IdxTy = Legal->getWidestInductionType();
  7183. PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
  7184. LoopVectorPreHeader->getFirstNonPHI());
  7185. EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
  7186. EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
  7187. EPI.MainLoopIterationCountCheck);
  7188. // Generate the induction variable.
  7189. createHeaderBranch(Lp);
  7190. // Generate induction resume values. These variables save the new starting
  7191. // indexes for the scalar loop. They are used to test if there are any tail
  7192. // iterations left once the vector loop has completed.
  7193. // Note that when the vectorized epilogue is skipped due to iteration count
  7194. // check, then the resume value for the induction variable comes from
  7195. // the trip count of the main vector loop, hence passing the AdditionalBypass
  7196. // argument.
  7197. createInductionResumeValues(Lp, {VecEpilogueIterationCountCheck,
  7198. EPI.VectorTripCount} /* AdditionalBypass */);
  7199. return {completeLoopSkeleton(Lp, OrigLoopID), EPResumeVal};
  7200. }
  7201. BasicBlock *
  7202. EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
  7203. Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
  7204. assert(EPI.TripCount &&
  7205. "Expected trip count to have been safed in the first pass.");
  7206. assert(
  7207. (!isa<Instruction>(EPI.TripCount) ||
  7208. DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
  7209. "saved trip count does not dominate insertion point.");
  7210. Value *TC = EPI.TripCount;
  7211. IRBuilder<> Builder(Insert->getTerminator());
  7212. Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
  7213. // Generate code to check if the loop's trip count is less than VF * UF of the
  7214. // vector epilogue loop.
  7215. auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
  7216. ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
  7217. Value *CheckMinIters =
  7218. Builder.CreateICmp(P, Count,
  7219. createStepForVF(Builder, Count->getType(),
  7220. EPI.EpilogueVF, EPI.EpilogueUF),
  7221. "min.epilog.iters.check");
  7222. ReplaceInstWithInst(
  7223. Insert->getTerminator(),
  7224. BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
  7225. LoopBypassBlocks.push_back(Insert);
  7226. return Insert;
  7227. }
  7228. void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
  7229. LLVM_DEBUG({
  7230. dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
  7231. << "Epilogue Loop VF:" << EPI.EpilogueVF
  7232. << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
  7233. });
  7234. }
  7235. void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
  7236. DEBUG_WITH_TYPE(VerboseDebug, {
  7237. dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
  7238. });
  7239. }
  7240. bool LoopVectorizationPlanner::getDecisionAndClampRange(
  7241. const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
  7242. assert(!Range.isEmpty() && "Trying to test an empty VF range.");
  7243. bool PredicateAtRangeStart = Predicate(Range.Start);
  7244. for (ElementCount TmpVF = Range.Start * 2;
  7245. ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
  7246. if (Predicate(TmpVF) != PredicateAtRangeStart) {
  7247. Range.End = TmpVF;
  7248. break;
  7249. }
  7250. return PredicateAtRangeStart;
  7251. }
  7252. /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
  7253. /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
  7254. /// of VF's starting at a given VF and extending it as much as possible. Each
  7255. /// vectorization decision can potentially shorten this sub-range during
  7256. /// buildVPlan().
  7257. void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
  7258. ElementCount MaxVF) {
  7259. auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
  7260. for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
  7261. VFRange SubRange = {VF, MaxVFPlusOne};
  7262. VPlans.push_back(buildVPlan(SubRange));
  7263. VF = SubRange.End;
  7264. }
  7265. }
  7266. VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
  7267. VPlanPtr &Plan) {
  7268. assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
  7269. // Look for cached value.
  7270. std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
  7271. EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
  7272. if (ECEntryIt != EdgeMaskCache.end())
  7273. return ECEntryIt->second;
  7274. VPValue *SrcMask = createBlockInMask(Src, Plan);
  7275. // The terminator has to be a branch inst!
  7276. BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
  7277. assert(BI && "Unexpected terminator found");
  7278. if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
  7279. return EdgeMaskCache[Edge] = SrcMask;
  7280. // If source is an exiting block, we know the exit edge is dynamically dead
  7281. // in the vector loop, and thus we don't need to restrict the mask. Avoid
  7282. // adding uses of an otherwise potentially dead instruction.
  7283. if (OrigLoop->isLoopExiting(Src))
  7284. return EdgeMaskCache[Edge] = SrcMask;
  7285. VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
  7286. assert(EdgeMask && "No Edge Mask found for condition");
  7287. if (BI->getSuccessor(0) != Dst)
  7288. EdgeMask = Builder.createNot(EdgeMask, BI->getDebugLoc());
  7289. if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
  7290. // The condition is 'SrcMask && EdgeMask', which is equivalent to
  7291. // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
  7292. // The select version does not introduce new UB if SrcMask is false and
  7293. // EdgeMask is poison. Using 'and' here introduces undefined behavior.
  7294. VPValue *False = Plan->getOrAddVPValue(
  7295. ConstantInt::getFalse(BI->getCondition()->getType()));
  7296. EdgeMask =
  7297. Builder.createSelect(SrcMask, EdgeMask, False, BI->getDebugLoc());
  7298. }
  7299. return EdgeMaskCache[Edge] = EdgeMask;
  7300. }
  7301. VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
  7302. assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
  7303. // Look for cached value.
  7304. BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
  7305. if (BCEntryIt != BlockMaskCache.end())
  7306. return BCEntryIt->second;
  7307. // All-one mask is modelled as no-mask following the convention for masked
  7308. // load/store/gather/scatter. Initialize BlockMask to no-mask.
  7309. VPValue *BlockMask = nullptr;
  7310. if (OrigLoop->getHeader() == BB) {
  7311. if (!CM.blockNeedsPredicationForAnyReason(BB))
  7312. return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
  7313. // Introduce the early-exit compare IV <= BTC to form header block mask.
  7314. // This is used instead of IV < TC because TC may wrap, unlike BTC. Start by
  7315. // constructing the desired canonical IV in the header block as its first
  7316. // non-phi instructions.
  7317. assert(CM.foldTailByMasking() && "must fold the tail");
  7318. VPBasicBlock *HeaderVPBB = Plan->getEntry()->getEntryBasicBlock();
  7319. auto NewInsertionPoint = HeaderVPBB->getFirstNonPhi();
  7320. auto *IV = new VPWidenCanonicalIVRecipe(Plan->getCanonicalIV());
  7321. HeaderVPBB->insert(IV, HeaderVPBB->getFirstNonPhi());
  7322. VPBuilder::InsertPointGuard Guard(Builder);
  7323. Builder.setInsertPoint(HeaderVPBB, NewInsertionPoint);
  7324. if (CM.TTI.emitGetActiveLaneMask()) {
  7325. VPValue *TC = Plan->getOrCreateTripCount();
  7326. BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV, TC});
  7327. } else {
  7328. VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
  7329. BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
  7330. }
  7331. return BlockMaskCache[BB] = BlockMask;
  7332. }
  7333. // This is the block mask. We OR all incoming edges.
  7334. for (auto *Predecessor : predecessors(BB)) {
  7335. VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
  7336. if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
  7337. return BlockMaskCache[BB] = EdgeMask;
  7338. if (!BlockMask) { // BlockMask has its initialized nullptr value.
  7339. BlockMask = EdgeMask;
  7340. continue;
  7341. }
  7342. BlockMask = Builder.createOr(BlockMask, EdgeMask, {});
  7343. }
  7344. return BlockMaskCache[BB] = BlockMask;
  7345. }
  7346. VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
  7347. ArrayRef<VPValue *> Operands,
  7348. VFRange &Range,
  7349. VPlanPtr &Plan) {
  7350. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  7351. "Must be called with either a load or store");
  7352. auto willWiden = [&](ElementCount VF) -> bool {
  7353. if (VF.isScalar())
  7354. return false;
  7355. LoopVectorizationCostModel::InstWidening Decision =
  7356. CM.getWideningDecision(I, VF);
  7357. assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
  7358. "CM decision should be taken at this point.");
  7359. if (Decision == LoopVectorizationCostModel::CM_Interleave)
  7360. return true;
  7361. if (CM.isScalarAfterVectorization(I, VF) ||
  7362. CM.isProfitableToScalarize(I, VF))
  7363. return false;
  7364. return Decision != LoopVectorizationCostModel::CM_Scalarize;
  7365. };
  7366. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  7367. return nullptr;
  7368. VPValue *Mask = nullptr;
  7369. if (Legal->isMaskRequired(I))
  7370. Mask = createBlockInMask(I->getParent(), Plan);
  7371. // Determine if the pointer operand of the access is either consecutive or
  7372. // reverse consecutive.
  7373. LoopVectorizationCostModel::InstWidening Decision =
  7374. CM.getWideningDecision(I, Range.Start);
  7375. bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
  7376. bool Consecutive =
  7377. Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
  7378. if (LoadInst *Load = dyn_cast<LoadInst>(I))
  7379. return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
  7380. Consecutive, Reverse);
  7381. StoreInst *Store = cast<StoreInst>(I);
  7382. return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
  7383. Mask, Consecutive, Reverse);
  7384. }
  7385. static VPWidenIntOrFpInductionRecipe *
  7386. createWidenInductionRecipe(PHINode *Phi, Instruction *PhiOrTrunc,
  7387. VPValue *Start, const InductionDescriptor &IndDesc,
  7388. LoopVectorizationCostModel &CM, Loop &OrigLoop,
  7389. VFRange &Range) {
  7390. // Returns true if an instruction \p I should be scalarized instead of
  7391. // vectorized for the chosen vectorization factor.
  7392. auto ShouldScalarizeInstruction = [&CM](Instruction *I, ElementCount VF) {
  7393. return CM.isScalarAfterVectorization(I, VF) ||
  7394. CM.isProfitableToScalarize(I, VF);
  7395. };
  7396. bool NeedsScalarIV = LoopVectorizationPlanner::getDecisionAndClampRange(
  7397. [&](ElementCount VF) {
  7398. // Returns true if we should generate a scalar version of \p IV.
  7399. if (ShouldScalarizeInstruction(PhiOrTrunc, VF))
  7400. return true;
  7401. auto isScalarInst = [&](User *U) -> bool {
  7402. auto *I = cast<Instruction>(U);
  7403. return OrigLoop.contains(I) && ShouldScalarizeInstruction(I, VF);
  7404. };
  7405. return any_of(PhiOrTrunc->users(), isScalarInst);
  7406. },
  7407. Range);
  7408. bool NeedsScalarIVOnly = LoopVectorizationPlanner::getDecisionAndClampRange(
  7409. [&](ElementCount VF) {
  7410. return ShouldScalarizeInstruction(PhiOrTrunc, VF);
  7411. },
  7412. Range);
  7413. assert(IndDesc.getStartValue() ==
  7414. Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()));
  7415. if (auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
  7416. return new VPWidenIntOrFpInductionRecipe(Phi, Start, IndDesc, TruncI,
  7417. NeedsScalarIV, !NeedsScalarIVOnly);
  7418. }
  7419. assert(isa<PHINode>(PhiOrTrunc) && "must be a phi node here");
  7420. return new VPWidenIntOrFpInductionRecipe(Phi, Start, IndDesc, NeedsScalarIV,
  7421. !NeedsScalarIVOnly);
  7422. }
  7423. VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionPHI(
  7424. PHINode *Phi, ArrayRef<VPValue *> Operands, VFRange &Range) const {
  7425. // Check if this is an integer or fp induction. If so, build the recipe that
  7426. // produces its scalar and vector values.
  7427. if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi))
  7428. return createWidenInductionRecipe(Phi, Phi, Operands[0], *II, CM, *OrigLoop,
  7429. Range);
  7430. return nullptr;
  7431. }
  7432. VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
  7433. TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
  7434. VPlan &Plan) const {
  7435. // Optimize the special case where the source is a constant integer
  7436. // induction variable. Notice that we can only optimize the 'trunc' case
  7437. // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
  7438. // (c) other casts depend on pointer size.
  7439. // Determine whether \p K is a truncation based on an induction variable that
  7440. // can be optimized.
  7441. auto isOptimizableIVTruncate =
  7442. [&](Instruction *K) -> std::function<bool(ElementCount)> {
  7443. return [=](ElementCount VF) -> bool {
  7444. return CM.isOptimizableIVTruncate(K, VF);
  7445. };
  7446. };
  7447. if (LoopVectorizationPlanner::getDecisionAndClampRange(
  7448. isOptimizableIVTruncate(I), Range)) {
  7449. auto *Phi = cast<PHINode>(I->getOperand(0));
  7450. const InductionDescriptor &II = *Legal->getIntOrFpInductionDescriptor(Phi);
  7451. VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
  7452. return createWidenInductionRecipe(Phi, I, Start, II, CM, *OrigLoop, Range);
  7453. }
  7454. return nullptr;
  7455. }
  7456. VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
  7457. ArrayRef<VPValue *> Operands,
  7458. VPlanPtr &Plan) {
  7459. // If all incoming values are equal, the incoming VPValue can be used directly
  7460. // instead of creating a new VPBlendRecipe.
  7461. VPValue *FirstIncoming = Operands[0];
  7462. if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
  7463. return FirstIncoming == Inc;
  7464. })) {
  7465. return Operands[0];
  7466. }
  7467. // We know that all PHIs in non-header blocks are converted into selects, so
  7468. // we don't have to worry about the insertion order and we can just use the
  7469. // builder. At this point we generate the predication tree. There may be
  7470. // duplications since this is a simple recursive scan, but future
  7471. // optimizations will clean it up.
  7472. SmallVector<VPValue *, 2> OperandsWithMask;
  7473. unsigned NumIncoming = Phi->getNumIncomingValues();
  7474. for (unsigned In = 0; In < NumIncoming; In++) {
  7475. VPValue *EdgeMask =
  7476. createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
  7477. assert((EdgeMask || NumIncoming == 1) &&
  7478. "Multiple predecessors with one having a full mask");
  7479. OperandsWithMask.push_back(Operands[In]);
  7480. if (EdgeMask)
  7481. OperandsWithMask.push_back(EdgeMask);
  7482. }
  7483. return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
  7484. }
  7485. VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
  7486. ArrayRef<VPValue *> Operands,
  7487. VFRange &Range) const {
  7488. bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
  7489. [this, CI](ElementCount VF) {
  7490. return CM.isScalarWithPredication(CI, VF);
  7491. },
  7492. Range);
  7493. if (IsPredicated)
  7494. return nullptr;
  7495. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  7496. if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
  7497. ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
  7498. ID == Intrinsic::pseudoprobe ||
  7499. ID == Intrinsic::experimental_noalias_scope_decl))
  7500. return nullptr;
  7501. auto willWiden = [&](ElementCount VF) -> bool {
  7502. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  7503. // The following case may be scalarized depending on the VF.
  7504. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  7505. // version of the instruction.
  7506. // Is it beneficial to perform intrinsic call compared to lib call?
  7507. bool NeedToScalarize = false;
  7508. InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
  7509. InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
  7510. bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
  7511. return UseVectorIntrinsic || !NeedToScalarize;
  7512. };
  7513. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  7514. return nullptr;
  7515. ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
  7516. return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
  7517. }
  7518. bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
  7519. assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
  7520. !isa<StoreInst>(I) && "Instruction should have been handled earlier");
  7521. // Instruction should be widened, unless it is scalar after vectorization,
  7522. // scalarization is profitable or it is predicated.
  7523. auto WillScalarize = [this, I](ElementCount VF) -> bool {
  7524. return CM.isScalarAfterVectorization(I, VF) ||
  7525. CM.isProfitableToScalarize(I, VF) ||
  7526. CM.isScalarWithPredication(I, VF);
  7527. };
  7528. return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
  7529. Range);
  7530. }
  7531. VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
  7532. ArrayRef<VPValue *> Operands) const {
  7533. auto IsVectorizableOpcode = [](unsigned Opcode) {
  7534. switch (Opcode) {
  7535. case Instruction::Add:
  7536. case Instruction::And:
  7537. case Instruction::AShr:
  7538. case Instruction::BitCast:
  7539. case Instruction::FAdd:
  7540. case Instruction::FCmp:
  7541. case Instruction::FDiv:
  7542. case Instruction::FMul:
  7543. case Instruction::FNeg:
  7544. case Instruction::FPExt:
  7545. case Instruction::FPToSI:
  7546. case Instruction::FPToUI:
  7547. case Instruction::FPTrunc:
  7548. case Instruction::FRem:
  7549. case Instruction::FSub:
  7550. case Instruction::ICmp:
  7551. case Instruction::IntToPtr:
  7552. case Instruction::LShr:
  7553. case Instruction::Mul:
  7554. case Instruction::Or:
  7555. case Instruction::PtrToInt:
  7556. case Instruction::SDiv:
  7557. case Instruction::Select:
  7558. case Instruction::SExt:
  7559. case Instruction::Shl:
  7560. case Instruction::SIToFP:
  7561. case Instruction::SRem:
  7562. case Instruction::Sub:
  7563. case Instruction::Trunc:
  7564. case Instruction::UDiv:
  7565. case Instruction::UIToFP:
  7566. case Instruction::URem:
  7567. case Instruction::Xor:
  7568. case Instruction::ZExt:
  7569. return true;
  7570. }
  7571. return false;
  7572. };
  7573. if (!IsVectorizableOpcode(I->getOpcode()))
  7574. return nullptr;
  7575. // Success: widen this instruction.
  7576. return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
  7577. }
  7578. void VPRecipeBuilder::fixHeaderPhis() {
  7579. BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
  7580. for (VPHeaderPHIRecipe *R : PhisToFix) {
  7581. auto *PN = cast<PHINode>(R->getUnderlyingValue());
  7582. VPRecipeBase *IncR =
  7583. getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
  7584. R->addOperand(IncR->getVPSingleValue());
  7585. }
  7586. }
  7587. VPBasicBlock *VPRecipeBuilder::handleReplication(
  7588. Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
  7589. VPlanPtr &Plan) {
  7590. bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
  7591. [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
  7592. Range);
  7593. bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
  7594. [&](ElementCount VF) { return CM.isPredicatedInst(I, VF, IsUniform); },
  7595. Range);
  7596. // Even if the instruction is not marked as uniform, there are certain
  7597. // intrinsic calls that can be effectively treated as such, so we check for
  7598. // them here. Conservatively, we only do this for scalable vectors, since
  7599. // for fixed-width VFs we can always fall back on full scalarization.
  7600. if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
  7601. switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
  7602. case Intrinsic::assume:
  7603. case Intrinsic::lifetime_start:
  7604. case Intrinsic::lifetime_end:
  7605. // For scalable vectors if one of the operands is variant then we still
  7606. // want to mark as uniform, which will generate one instruction for just
  7607. // the first lane of the vector. We can't scalarize the call in the same
  7608. // way as for fixed-width vectors because we don't know how many lanes
  7609. // there are.
  7610. //
  7611. // The reasons for doing it this way for scalable vectors are:
  7612. // 1. For the assume intrinsic generating the instruction for the first
  7613. // lane is still be better than not generating any at all. For
  7614. // example, the input may be a splat across all lanes.
  7615. // 2. For the lifetime start/end intrinsics the pointer operand only
  7616. // does anything useful when the input comes from a stack object,
  7617. // which suggests it should always be uniform. For non-stack objects
  7618. // the effect is to poison the object, which still allows us to
  7619. // remove the call.
  7620. IsUniform = true;
  7621. break;
  7622. default:
  7623. break;
  7624. }
  7625. }
  7626. auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
  7627. IsUniform, IsPredicated);
  7628. setRecipe(I, Recipe);
  7629. Plan->addVPValue(I, Recipe);
  7630. // Find if I uses a predicated instruction. If so, it will use its scalar
  7631. // value. Avoid hoisting the insert-element which packs the scalar value into
  7632. // a vector value, as that happens iff all users use the vector value.
  7633. for (VPValue *Op : Recipe->operands()) {
  7634. auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
  7635. if (!PredR)
  7636. continue;
  7637. auto *RepR =
  7638. cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
  7639. assert(RepR->isPredicated() &&
  7640. "expected Replicate recipe to be predicated");
  7641. RepR->setAlsoPack(false);
  7642. }
  7643. // Finalize the recipe for Instr, first if it is not predicated.
  7644. if (!IsPredicated) {
  7645. LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
  7646. VPBB->appendRecipe(Recipe);
  7647. return VPBB;
  7648. }
  7649. LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
  7650. VPBlockBase *SingleSucc = VPBB->getSingleSuccessor();
  7651. assert(SingleSucc && "VPBB must have a single successor when handling "
  7652. "predicated replication.");
  7653. VPBlockUtils::disconnectBlocks(VPBB, SingleSucc);
  7654. // Record predicated instructions for above packing optimizations.
  7655. VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
  7656. VPBlockUtils::insertBlockAfter(Region, VPBB);
  7657. auto *RegSucc = new VPBasicBlock();
  7658. VPBlockUtils::insertBlockAfter(RegSucc, Region);
  7659. VPBlockUtils::connectBlocks(RegSucc, SingleSucc);
  7660. return RegSucc;
  7661. }
  7662. VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
  7663. VPRecipeBase *PredRecipe,
  7664. VPlanPtr &Plan) {
  7665. // Instructions marked for predication are replicated and placed under an
  7666. // if-then construct to prevent side-effects.
  7667. // Generate recipes to compute the block mask for this region.
  7668. VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
  7669. // Build the triangular if-then region.
  7670. std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
  7671. assert(Instr->getParent() && "Predicated instruction not in any basic block");
  7672. auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
  7673. auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
  7674. auto *PHIRecipe = Instr->getType()->isVoidTy()
  7675. ? nullptr
  7676. : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
  7677. if (PHIRecipe) {
  7678. Plan->removeVPValueFor(Instr);
  7679. Plan->addVPValue(Instr, PHIRecipe);
  7680. }
  7681. auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
  7682. auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
  7683. VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
  7684. // Note: first set Entry as region entry and then connect successors starting
  7685. // from it in order, to propagate the "parent" of each VPBasicBlock.
  7686. VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
  7687. VPBlockUtils::connectBlocks(Pred, Exit);
  7688. return Region;
  7689. }
  7690. VPRecipeOrVPValueTy
  7691. VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
  7692. ArrayRef<VPValue *> Operands,
  7693. VFRange &Range, VPlanPtr &Plan) {
  7694. // First, check for specific widening recipes that deal with calls, memory
  7695. // operations, inductions and Phi nodes.
  7696. if (auto *CI = dyn_cast<CallInst>(Instr))
  7697. return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
  7698. if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
  7699. return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
  7700. VPRecipeBase *Recipe;
  7701. if (auto Phi = dyn_cast<PHINode>(Instr)) {
  7702. if (Phi->getParent() != OrigLoop->getHeader())
  7703. return tryToBlend(Phi, Operands, Plan);
  7704. if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands, Range)))
  7705. return toVPRecipeResult(Recipe);
  7706. VPHeaderPHIRecipe *PhiRecipe = nullptr;
  7707. if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
  7708. VPValue *StartV = Operands[0];
  7709. if (Legal->isReductionVariable(Phi)) {
  7710. const RecurrenceDescriptor &RdxDesc =
  7711. Legal->getReductionVars().find(Phi)->second;
  7712. assert(RdxDesc.getRecurrenceStartValue() ==
  7713. Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
  7714. PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
  7715. CM.isInLoopReduction(Phi),
  7716. CM.useOrderedReductions(RdxDesc));
  7717. } else {
  7718. PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
  7719. }
  7720. // Record the incoming value from the backedge, so we can add the incoming
  7721. // value from the backedge after all recipes have been created.
  7722. recordRecipeOf(cast<Instruction>(
  7723. Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
  7724. PhisToFix.push_back(PhiRecipe);
  7725. } else {
  7726. // TODO: record backedge value for remaining pointer induction phis.
  7727. assert(Phi->getType()->isPointerTy() &&
  7728. "only pointer phis should be handled here");
  7729. assert(Legal->getInductionVars().count(Phi) &&
  7730. "Not an induction variable");
  7731. InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
  7732. VPValue *Start = Plan->getOrAddVPValue(II.getStartValue());
  7733. PhiRecipe = new VPWidenPHIRecipe(Phi, Start);
  7734. }
  7735. return toVPRecipeResult(PhiRecipe);
  7736. }
  7737. if (isa<TruncInst>(Instr) &&
  7738. (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
  7739. Range, *Plan)))
  7740. return toVPRecipeResult(Recipe);
  7741. if (!shouldWiden(Instr, Range))
  7742. return nullptr;
  7743. if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
  7744. return toVPRecipeResult(new VPWidenGEPRecipe(
  7745. GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
  7746. if (auto *SI = dyn_cast<SelectInst>(Instr)) {
  7747. bool InvariantCond =
  7748. PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
  7749. return toVPRecipeResult(new VPWidenSelectRecipe(
  7750. *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
  7751. }
  7752. return toVPRecipeResult(tryToWiden(Instr, Operands));
  7753. }
  7754. void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
  7755. ElementCount MaxVF) {
  7756. assert(OrigLoop->isInnermost() && "Inner loop expected.");
  7757. // Collect instructions from the original loop that will become trivially dead
  7758. // in the vectorized loop. We don't need to vectorize these instructions. For
  7759. // example, original induction update instructions can become dead because we
  7760. // separately emit induction "steps" when generating code for the new loop.
  7761. // Similarly, we create a new latch condition when setting up the structure
  7762. // of the new loop, so the old one can become dead.
  7763. SmallPtrSet<Instruction *, 4> DeadInstructions;
  7764. collectTriviallyDeadInstructions(DeadInstructions);
  7765. // Add assume instructions we need to drop to DeadInstructions, to prevent
  7766. // them from being added to the VPlan.
  7767. // TODO: We only need to drop assumes in blocks that get flattend. If the
  7768. // control flow is preserved, we should keep them.
  7769. auto &ConditionalAssumes = Legal->getConditionalAssumes();
  7770. DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
  7771. MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
  7772. // Dead instructions do not need sinking. Remove them from SinkAfter.
  7773. for (Instruction *I : DeadInstructions)
  7774. SinkAfter.erase(I);
  7775. // Cannot sink instructions after dead instructions (there won't be any
  7776. // recipes for them). Instead, find the first non-dead previous instruction.
  7777. for (auto &P : Legal->getSinkAfter()) {
  7778. Instruction *SinkTarget = P.second;
  7779. Instruction *FirstInst = &*SinkTarget->getParent()->begin();
  7780. (void)FirstInst;
  7781. while (DeadInstructions.contains(SinkTarget)) {
  7782. assert(
  7783. SinkTarget != FirstInst &&
  7784. "Must find a live instruction (at least the one feeding the "
  7785. "first-order recurrence PHI) before reaching beginning of the block");
  7786. SinkTarget = SinkTarget->getPrevNode();
  7787. assert(SinkTarget != P.first &&
  7788. "sink source equals target, no sinking required");
  7789. }
  7790. P.second = SinkTarget;
  7791. }
  7792. auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
  7793. for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
  7794. VFRange SubRange = {VF, MaxVFPlusOne};
  7795. VPlans.push_back(
  7796. buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
  7797. VF = SubRange.End;
  7798. }
  7799. }
  7800. // Add a VPCanonicalIVPHIRecipe starting at 0 to the header, a
  7801. // CanonicalIVIncrement{NUW} VPInstruction to increment it by VF * UF and a
  7802. // BranchOnCount VPInstruction to the latch.
  7803. static void addCanonicalIVRecipes(VPlan &Plan, Type *IdxTy, DebugLoc DL,
  7804. bool HasNUW, bool IsVPlanNative) {
  7805. Value *StartIdx = ConstantInt::get(IdxTy, 0);
  7806. auto *StartV = Plan.getOrAddVPValue(StartIdx);
  7807. auto *CanonicalIVPHI = new VPCanonicalIVPHIRecipe(StartV, DL);
  7808. VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
  7809. VPBasicBlock *Header = TopRegion->getEntryBasicBlock();
  7810. if (IsVPlanNative)
  7811. Header = cast<VPBasicBlock>(Header->getSingleSuccessor());
  7812. Header->insert(CanonicalIVPHI, Header->begin());
  7813. auto *CanonicalIVIncrement =
  7814. new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementNUW
  7815. : VPInstruction::CanonicalIVIncrement,
  7816. {CanonicalIVPHI}, DL);
  7817. CanonicalIVPHI->addOperand(CanonicalIVIncrement);
  7818. VPBasicBlock *EB = TopRegion->getExitBasicBlock();
  7819. if (IsVPlanNative) {
  7820. EB = cast<VPBasicBlock>(EB->getSinglePredecessor());
  7821. EB->setCondBit(nullptr);
  7822. }
  7823. EB->appendRecipe(CanonicalIVIncrement);
  7824. auto *BranchOnCount =
  7825. new VPInstruction(VPInstruction::BranchOnCount,
  7826. {CanonicalIVIncrement, &Plan.getVectorTripCount()}, DL);
  7827. EB->appendRecipe(BranchOnCount);
  7828. }
  7829. VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
  7830. VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
  7831. const MapVector<Instruction *, Instruction *> &SinkAfter) {
  7832. SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
  7833. VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
  7834. // ---------------------------------------------------------------------------
  7835. // Pre-construction: record ingredients whose recipes we'll need to further
  7836. // process after constructing the initial VPlan.
  7837. // ---------------------------------------------------------------------------
  7838. // Mark instructions we'll need to sink later and their targets as
  7839. // ingredients whose recipe we'll need to record.
  7840. for (auto &Entry : SinkAfter) {
  7841. RecipeBuilder.recordRecipeOf(Entry.first);
  7842. RecipeBuilder.recordRecipeOf(Entry.second);
  7843. }
  7844. for (auto &Reduction : CM.getInLoopReductionChains()) {
  7845. PHINode *Phi = Reduction.first;
  7846. RecurKind Kind =
  7847. Legal->getReductionVars().find(Phi)->second.getRecurrenceKind();
  7848. const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
  7849. RecipeBuilder.recordRecipeOf(Phi);
  7850. for (auto &R : ReductionOperations) {
  7851. RecipeBuilder.recordRecipeOf(R);
  7852. // For min/max reducitons, where we have a pair of icmp/select, we also
  7853. // need to record the ICmp recipe, so it can be removed later.
  7854. assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
  7855. "Only min/max recurrences allowed for inloop reductions");
  7856. if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
  7857. RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
  7858. }
  7859. }
  7860. // For each interleave group which is relevant for this (possibly trimmed)
  7861. // Range, add it to the set of groups to be later applied to the VPlan and add
  7862. // placeholders for its members' Recipes which we'll be replacing with a
  7863. // single VPInterleaveRecipe.
  7864. for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
  7865. auto applyIG = [IG, this](ElementCount VF) -> bool {
  7866. return (VF.isVector() && // Query is illegal for VF == 1
  7867. CM.getWideningDecision(IG->getInsertPos(), VF) ==
  7868. LoopVectorizationCostModel::CM_Interleave);
  7869. };
  7870. if (!getDecisionAndClampRange(applyIG, Range))
  7871. continue;
  7872. InterleaveGroups.insert(IG);
  7873. for (unsigned i = 0; i < IG->getFactor(); i++)
  7874. if (Instruction *Member = IG->getMember(i))
  7875. RecipeBuilder.recordRecipeOf(Member);
  7876. };
  7877. // ---------------------------------------------------------------------------
  7878. // Build initial VPlan: Scan the body of the loop in a topological order to
  7879. // visit each basic block after having visited its predecessor basic blocks.
  7880. // ---------------------------------------------------------------------------
  7881. // Create initial VPlan skeleton, with separate header and latch blocks.
  7882. VPBasicBlock *HeaderVPBB = new VPBasicBlock();
  7883. VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
  7884. VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
  7885. auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop");
  7886. auto Plan = std::make_unique<VPlan>(TopRegion);
  7887. Instruction *DLInst =
  7888. getDebugLocFromInstOrOperands(Legal->getPrimaryInduction());
  7889. addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(),
  7890. DLInst ? DLInst->getDebugLoc() : DebugLoc(),
  7891. !CM.foldTailByMasking(), false);
  7892. // Scan the body of the loop in a topological order to visit each basic block
  7893. // after having visited its predecessor basic blocks.
  7894. LoopBlocksDFS DFS(OrigLoop);
  7895. DFS.perform(LI);
  7896. VPBasicBlock *VPBB = HeaderVPBB;
  7897. SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
  7898. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  7899. // Relevant instructions from basic block BB will be grouped into VPRecipe
  7900. // ingredients and fill a new VPBasicBlock.
  7901. unsigned VPBBsForBB = 0;
  7902. VPBB->setName(BB->getName());
  7903. Builder.setInsertPoint(VPBB);
  7904. // Introduce each ingredient into VPlan.
  7905. // TODO: Model and preserve debug instrinsics in VPlan.
  7906. for (Instruction &I : BB->instructionsWithoutDebug()) {
  7907. Instruction *Instr = &I;
  7908. // First filter out irrelevant instructions, to ensure no recipes are
  7909. // built for them.
  7910. if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
  7911. continue;
  7912. SmallVector<VPValue *, 4> Operands;
  7913. auto *Phi = dyn_cast<PHINode>(Instr);
  7914. if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
  7915. Operands.push_back(Plan->getOrAddVPValue(
  7916. Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
  7917. } else {
  7918. auto OpRange = Plan->mapToVPValues(Instr->operands());
  7919. Operands = {OpRange.begin(), OpRange.end()};
  7920. }
  7921. if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
  7922. Instr, Operands, Range, Plan)) {
  7923. // If Instr can be simplified to an existing VPValue, use it.
  7924. if (RecipeOrValue.is<VPValue *>()) {
  7925. auto *VPV = RecipeOrValue.get<VPValue *>();
  7926. Plan->addVPValue(Instr, VPV);
  7927. // If the re-used value is a recipe, register the recipe for the
  7928. // instruction, in case the recipe for Instr needs to be recorded.
  7929. if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
  7930. RecipeBuilder.setRecipe(Instr, R);
  7931. continue;
  7932. }
  7933. // Otherwise, add the new recipe.
  7934. VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
  7935. for (auto *Def : Recipe->definedValues()) {
  7936. auto *UV = Def->getUnderlyingValue();
  7937. Plan->addVPValue(UV, Def);
  7938. }
  7939. if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
  7940. HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
  7941. // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
  7942. // of the header block. That can happen for truncates of induction
  7943. // variables. Those recipes are moved to the phi section of the header
  7944. // block after applying SinkAfter, which relies on the original
  7945. // position of the trunc.
  7946. assert(isa<TruncInst>(Instr));
  7947. InductionsToMove.push_back(
  7948. cast<VPWidenIntOrFpInductionRecipe>(Recipe));
  7949. }
  7950. RecipeBuilder.setRecipe(Instr, Recipe);
  7951. VPBB->appendRecipe(Recipe);
  7952. continue;
  7953. }
  7954. // Otherwise, if all widening options failed, Instruction is to be
  7955. // replicated. This may create a successor for VPBB.
  7956. VPBasicBlock *NextVPBB =
  7957. RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
  7958. if (NextVPBB != VPBB) {
  7959. VPBB = NextVPBB;
  7960. VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
  7961. : "");
  7962. }
  7963. }
  7964. VPBlockUtils::insertBlockAfter(new VPBasicBlock(), VPBB);
  7965. VPBB = cast<VPBasicBlock>(VPBB->getSingleSuccessor());
  7966. }
  7967. // Fold the last, empty block into its predecessor.
  7968. VPBB = VPBlockUtils::tryToMergeBlockIntoPredecessor(VPBB);
  7969. assert(VPBB && "expected to fold last (empty) block");
  7970. // After here, VPBB should not be used.
  7971. VPBB = nullptr;
  7972. assert(isa<VPRegionBlock>(Plan->getEntry()) &&
  7973. !Plan->getEntry()->getEntryBasicBlock()->empty() &&
  7974. "entry block must be set to a VPRegionBlock having a non-empty entry "
  7975. "VPBasicBlock");
  7976. RecipeBuilder.fixHeaderPhis();
  7977. // ---------------------------------------------------------------------------
  7978. // Transform initial VPlan: Apply previously taken decisions, in order, to
  7979. // bring the VPlan to its final state.
  7980. // ---------------------------------------------------------------------------
  7981. // Apply Sink-After legal constraints.
  7982. auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
  7983. auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
  7984. if (Region && Region->isReplicator()) {
  7985. assert(Region->getNumSuccessors() == 1 &&
  7986. Region->getNumPredecessors() == 1 && "Expected SESE region!");
  7987. assert(R->getParent()->size() == 1 &&
  7988. "A recipe in an original replicator region must be the only "
  7989. "recipe in its block");
  7990. return Region;
  7991. }
  7992. return nullptr;
  7993. };
  7994. for (auto &Entry : SinkAfter) {
  7995. VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
  7996. VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
  7997. auto *TargetRegion = GetReplicateRegion(Target);
  7998. auto *SinkRegion = GetReplicateRegion(Sink);
  7999. if (!SinkRegion) {
  8000. // If the sink source is not a replicate region, sink the recipe directly.
  8001. if (TargetRegion) {
  8002. // The target is in a replication region, make sure to move Sink to
  8003. // the block after it, not into the replication region itself.
  8004. VPBasicBlock *NextBlock =
  8005. cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
  8006. Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
  8007. } else
  8008. Sink->moveAfter(Target);
  8009. continue;
  8010. }
  8011. // The sink source is in a replicate region. Unhook the region from the CFG.
  8012. auto *SinkPred = SinkRegion->getSinglePredecessor();
  8013. auto *SinkSucc = SinkRegion->getSingleSuccessor();
  8014. VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
  8015. VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
  8016. VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
  8017. if (TargetRegion) {
  8018. // The target recipe is also in a replicate region, move the sink region
  8019. // after the target region.
  8020. auto *TargetSucc = TargetRegion->getSingleSuccessor();
  8021. VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
  8022. VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
  8023. VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
  8024. } else {
  8025. // The sink source is in a replicate region, we need to move the whole
  8026. // replicate region, which should only contain a single recipe in the
  8027. // main block.
  8028. auto *SplitBlock =
  8029. Target->getParent()->splitAt(std::next(Target->getIterator()));
  8030. auto *SplitPred = SplitBlock->getSinglePredecessor();
  8031. VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
  8032. VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
  8033. VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
  8034. }
  8035. }
  8036. VPlanTransforms::removeRedundantCanonicalIVs(*Plan);
  8037. VPlanTransforms::removeRedundantInductionCasts(*Plan);
  8038. // Now that sink-after is done, move induction recipes for optimized truncates
  8039. // to the phi section of the header block.
  8040. for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
  8041. Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
  8042. // Adjust the recipes for any inloop reductions.
  8043. adjustRecipesForReductions(cast<VPBasicBlock>(TopRegion->getExit()), Plan,
  8044. RecipeBuilder, Range.Start);
  8045. // Introduce a recipe to combine the incoming and previous values of a
  8046. // first-order recurrence.
  8047. for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
  8048. auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
  8049. if (!RecurPhi)
  8050. continue;
  8051. VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
  8052. VPBasicBlock *InsertBlock = PrevRecipe->getParent();
  8053. auto *Region = GetReplicateRegion(PrevRecipe);
  8054. if (Region)
  8055. InsertBlock = cast<VPBasicBlock>(Region->getSingleSuccessor());
  8056. if (Region || PrevRecipe->isPhi())
  8057. Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
  8058. else
  8059. Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
  8060. auto *RecurSplice = cast<VPInstruction>(
  8061. Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
  8062. {RecurPhi, RecurPhi->getBackedgeValue()}));
  8063. RecurPhi->replaceAllUsesWith(RecurSplice);
  8064. // Set the first operand of RecurSplice to RecurPhi again, after replacing
  8065. // all users.
  8066. RecurSplice->setOperand(0, RecurPhi);
  8067. }
  8068. // Interleave memory: for each Interleave Group we marked earlier as relevant
  8069. // for this VPlan, replace the Recipes widening its memory instructions with a
  8070. // single VPInterleaveRecipe at its insertion point.
  8071. for (auto IG : InterleaveGroups) {
  8072. auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
  8073. RecipeBuilder.getRecipe(IG->getInsertPos()));
  8074. SmallVector<VPValue *, 4> StoredValues;
  8075. for (unsigned i = 0; i < IG->getFactor(); ++i)
  8076. if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
  8077. auto *StoreR =
  8078. cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
  8079. StoredValues.push_back(StoreR->getStoredValue());
  8080. }
  8081. auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
  8082. Recipe->getMask());
  8083. VPIG->insertBefore(Recipe);
  8084. unsigned J = 0;
  8085. for (unsigned i = 0; i < IG->getFactor(); ++i)
  8086. if (Instruction *Member = IG->getMember(i)) {
  8087. if (!Member->getType()->isVoidTy()) {
  8088. VPValue *OriginalV = Plan->getVPValue(Member);
  8089. Plan->removeVPValueFor(Member);
  8090. Plan->addVPValue(Member, VPIG->getVPValue(J));
  8091. OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
  8092. J++;
  8093. }
  8094. RecipeBuilder.getRecipe(Member)->eraseFromParent();
  8095. }
  8096. }
  8097. // From this point onwards, VPlan-to-VPlan transformations may change the plan
  8098. // in ways that accessing values using original IR values is incorrect.
  8099. Plan->disableValue2VPValue();
  8100. VPlanTransforms::sinkScalarOperands(*Plan);
  8101. VPlanTransforms::mergeReplicateRegions(*Plan);
  8102. std::string PlanName;
  8103. raw_string_ostream RSO(PlanName);
  8104. ElementCount VF = Range.Start;
  8105. Plan->addVF(VF);
  8106. RSO << "Initial VPlan for VF={" << VF;
  8107. for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
  8108. Plan->addVF(VF);
  8109. RSO << "," << VF;
  8110. }
  8111. RSO << "},UF>=1";
  8112. RSO.flush();
  8113. Plan->setName(PlanName);
  8114. // Fold Exit block into its predecessor if possible.
  8115. // TODO: Fold block earlier once all VPlan transforms properly maintain a
  8116. // VPBasicBlock as exit.
  8117. VPBlockUtils::tryToMergeBlockIntoPredecessor(TopRegion->getExit());
  8118. assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
  8119. return Plan;
  8120. }
  8121. VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
  8122. // Outer loop handling: They may require CFG and instruction level
  8123. // transformations before even evaluating whether vectorization is profitable.
  8124. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  8125. // the vectorization pipeline.
  8126. assert(!OrigLoop->isInnermost());
  8127. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  8128. // Create new empty VPlan
  8129. auto Plan = std::make_unique<VPlan>();
  8130. // Build hierarchical CFG
  8131. VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
  8132. HCFGBuilder.buildHierarchicalCFG();
  8133. for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
  8134. VF *= 2)
  8135. Plan->addVF(VF);
  8136. if (EnableVPlanPredication) {
  8137. VPlanPredicator VPP(*Plan);
  8138. VPP.predicate();
  8139. // Avoid running transformation to recipes until masked code generation in
  8140. // VPlan-native path is in place.
  8141. return Plan;
  8142. }
  8143. SmallPtrSet<Instruction *, 1> DeadInstructions;
  8144. VPlanTransforms::VPInstructionsToVPRecipes(
  8145. OrigLoop, Plan,
  8146. [this](PHINode *P) { return Legal->getIntOrFpInductionDescriptor(P); },
  8147. DeadInstructions, *PSE.getSE());
  8148. addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(), DebugLoc(),
  8149. true, true);
  8150. return Plan;
  8151. }
  8152. // Adjust the recipes for reductions. For in-loop reductions the chain of
  8153. // instructions leading from the loop exit instr to the phi need to be converted
  8154. // to reductions, with one operand being vector and the other being the scalar
  8155. // reduction chain. For other reductions, a select is introduced between the phi
  8156. // and live-out recipes when folding the tail.
  8157. void LoopVectorizationPlanner::adjustRecipesForReductions(
  8158. VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
  8159. ElementCount MinVF) {
  8160. for (auto &Reduction : CM.getInLoopReductionChains()) {
  8161. PHINode *Phi = Reduction.first;
  8162. const RecurrenceDescriptor &RdxDesc =
  8163. Legal->getReductionVars().find(Phi)->second;
  8164. const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
  8165. if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
  8166. continue;
  8167. // ReductionOperations are orders top-down from the phi's use to the
  8168. // LoopExitValue. We keep a track of the previous item (the Chain) to tell
  8169. // which of the two operands will remain scalar and which will be reduced.
  8170. // For minmax the chain will be the select instructions.
  8171. Instruction *Chain = Phi;
  8172. for (Instruction *R : ReductionOperations) {
  8173. VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
  8174. RecurKind Kind = RdxDesc.getRecurrenceKind();
  8175. VPValue *ChainOp = Plan->getVPValue(Chain);
  8176. unsigned FirstOpId;
  8177. assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
  8178. "Only min/max recurrences allowed for inloop reductions");
  8179. // Recognize a call to the llvm.fmuladd intrinsic.
  8180. bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
  8181. assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
  8182. "Expected instruction to be a call to the llvm.fmuladd intrinsic");
  8183. if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
  8184. assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
  8185. "Expected to replace a VPWidenSelectSC");
  8186. FirstOpId = 1;
  8187. } else {
  8188. assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
  8189. (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
  8190. "Expected to replace a VPWidenSC");
  8191. FirstOpId = 0;
  8192. }
  8193. unsigned VecOpId =
  8194. R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
  8195. VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
  8196. auto *CondOp = CM.foldTailByMasking()
  8197. ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
  8198. : nullptr;
  8199. if (IsFMulAdd) {
  8200. // If the instruction is a call to the llvm.fmuladd intrinsic then we
  8201. // need to create an fmul recipe to use as the vector operand for the
  8202. // fadd reduction.
  8203. VPInstruction *FMulRecipe = new VPInstruction(
  8204. Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
  8205. FMulRecipe->setFastMathFlags(R->getFastMathFlags());
  8206. WidenRecipe->getParent()->insert(FMulRecipe,
  8207. WidenRecipe->getIterator());
  8208. VecOp = FMulRecipe;
  8209. }
  8210. VPReductionRecipe *RedRecipe =
  8211. new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
  8212. WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
  8213. Plan->removeVPValueFor(R);
  8214. Plan->addVPValue(R, RedRecipe);
  8215. WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
  8216. WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
  8217. WidenRecipe->eraseFromParent();
  8218. if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
  8219. VPRecipeBase *CompareRecipe =
  8220. RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
  8221. assert(isa<VPWidenRecipe>(CompareRecipe) &&
  8222. "Expected to replace a VPWidenSC");
  8223. assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
  8224. "Expected no remaining users");
  8225. CompareRecipe->eraseFromParent();
  8226. }
  8227. Chain = R;
  8228. }
  8229. }
  8230. // If tail is folded by masking, introduce selects between the phi
  8231. // and the live-out instruction of each reduction, at the beginning of the
  8232. // dedicated latch block.
  8233. if (CM.foldTailByMasking()) {
  8234. Builder.setInsertPoint(LatchVPBB, LatchVPBB->begin());
  8235. for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
  8236. VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
  8237. if (!PhiR || PhiR->isInLoop())
  8238. continue;
  8239. VPValue *Cond =
  8240. RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
  8241. VPValue *Red = PhiR->getBackedgeValue();
  8242. assert(cast<VPRecipeBase>(Red->getDef())->getParent() != LatchVPBB &&
  8243. "reduction recipe must be defined before latch");
  8244. Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
  8245. }
  8246. }
  8247. }
  8248. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  8249. void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
  8250. VPSlotTracker &SlotTracker) const {
  8251. O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
  8252. IG->getInsertPos()->printAsOperand(O, false);
  8253. O << ", ";
  8254. getAddr()->printAsOperand(O, SlotTracker);
  8255. VPValue *Mask = getMask();
  8256. if (Mask) {
  8257. O << ", ";
  8258. Mask->printAsOperand(O, SlotTracker);
  8259. }
  8260. unsigned OpIdx = 0;
  8261. for (unsigned i = 0; i < IG->getFactor(); ++i) {
  8262. if (!IG->getMember(i))
  8263. continue;
  8264. if (getNumStoreOperands() > 0) {
  8265. O << "\n" << Indent << " store ";
  8266. getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
  8267. O << " to index " << i;
  8268. } else {
  8269. O << "\n" << Indent << " ";
  8270. getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
  8271. O << " = load from index " << i;
  8272. }
  8273. ++OpIdx;
  8274. }
  8275. }
  8276. #endif
  8277. void VPWidenCallRecipe::execute(VPTransformState &State) {
  8278. State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
  8279. *this, State);
  8280. }
  8281. void VPWidenSelectRecipe::execute(VPTransformState &State) {
  8282. auto &I = *cast<SelectInst>(getUnderlyingInstr());
  8283. State.ILV->setDebugLocFromInst(&I);
  8284. // The condition can be loop invariant but still defined inside the
  8285. // loop. This means that we can't just use the original 'cond' value.
  8286. // We have to take the 'vectorized' value and pick the first lane.
  8287. // Instcombine will make this a no-op.
  8288. auto *InvarCond =
  8289. InvariantCond ? State.get(getOperand(0), VPIteration(0, 0)) : nullptr;
  8290. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8291. Value *Cond = InvarCond ? InvarCond : State.get(getOperand(0), Part);
  8292. Value *Op0 = State.get(getOperand(1), Part);
  8293. Value *Op1 = State.get(getOperand(2), Part);
  8294. Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
  8295. State.set(this, Sel, Part);
  8296. State.ILV->addMetadata(Sel, &I);
  8297. }
  8298. }
  8299. void VPWidenRecipe::execute(VPTransformState &State) {
  8300. auto &I = *cast<Instruction>(getUnderlyingValue());
  8301. auto &Builder = State.Builder;
  8302. switch (I.getOpcode()) {
  8303. case Instruction::Call:
  8304. case Instruction::Br:
  8305. case Instruction::PHI:
  8306. case Instruction::GetElementPtr:
  8307. case Instruction::Select:
  8308. llvm_unreachable("This instruction is handled by a different recipe.");
  8309. case Instruction::UDiv:
  8310. case Instruction::SDiv:
  8311. case Instruction::SRem:
  8312. case Instruction::URem:
  8313. case Instruction::Add:
  8314. case Instruction::FAdd:
  8315. case Instruction::Sub:
  8316. case Instruction::FSub:
  8317. case Instruction::FNeg:
  8318. case Instruction::Mul:
  8319. case Instruction::FMul:
  8320. case Instruction::FDiv:
  8321. case Instruction::FRem:
  8322. case Instruction::Shl:
  8323. case Instruction::LShr:
  8324. case Instruction::AShr:
  8325. case Instruction::And:
  8326. case Instruction::Or:
  8327. case Instruction::Xor: {
  8328. // Just widen unops and binops.
  8329. State.ILV->setDebugLocFromInst(&I);
  8330. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8331. SmallVector<Value *, 2> Ops;
  8332. for (VPValue *VPOp : operands())
  8333. Ops.push_back(State.get(VPOp, Part));
  8334. Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
  8335. if (auto *VecOp = dyn_cast<Instruction>(V)) {
  8336. VecOp->copyIRFlags(&I);
  8337. // If the instruction is vectorized and was in a basic block that needed
  8338. // predication, we can't propagate poison-generating flags (nuw/nsw,
  8339. // exact, etc.). The control flow has been linearized and the
  8340. // instruction is no longer guarded by the predicate, which could make
  8341. // the flag properties to no longer hold.
  8342. if (State.MayGeneratePoisonRecipes.contains(this))
  8343. VecOp->dropPoisonGeneratingFlags();
  8344. }
  8345. // Use this vector value for all users of the original instruction.
  8346. State.set(this, V, Part);
  8347. State.ILV->addMetadata(V, &I);
  8348. }
  8349. break;
  8350. }
  8351. case Instruction::ICmp:
  8352. case Instruction::FCmp: {
  8353. // Widen compares. Generate vector compares.
  8354. bool FCmp = (I.getOpcode() == Instruction::FCmp);
  8355. auto *Cmp = cast<CmpInst>(&I);
  8356. State.ILV->setDebugLocFromInst(Cmp);
  8357. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8358. Value *A = State.get(getOperand(0), Part);
  8359. Value *B = State.get(getOperand(1), Part);
  8360. Value *C = nullptr;
  8361. if (FCmp) {
  8362. // Propagate fast math flags.
  8363. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  8364. Builder.setFastMathFlags(Cmp->getFastMathFlags());
  8365. C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
  8366. } else {
  8367. C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
  8368. }
  8369. State.set(this, C, Part);
  8370. State.ILV->addMetadata(C, &I);
  8371. }
  8372. break;
  8373. }
  8374. case Instruction::ZExt:
  8375. case Instruction::SExt:
  8376. case Instruction::FPToUI:
  8377. case Instruction::FPToSI:
  8378. case Instruction::FPExt:
  8379. case Instruction::PtrToInt:
  8380. case Instruction::IntToPtr:
  8381. case Instruction::SIToFP:
  8382. case Instruction::UIToFP:
  8383. case Instruction::Trunc:
  8384. case Instruction::FPTrunc:
  8385. case Instruction::BitCast: {
  8386. auto *CI = cast<CastInst>(&I);
  8387. State.ILV->setDebugLocFromInst(CI);
  8388. /// Vectorize casts.
  8389. Type *DestTy = (State.VF.isScalar())
  8390. ? CI->getType()
  8391. : VectorType::get(CI->getType(), State.VF);
  8392. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8393. Value *A = State.get(getOperand(0), Part);
  8394. Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
  8395. State.set(this, Cast, Part);
  8396. State.ILV->addMetadata(Cast, &I);
  8397. }
  8398. break;
  8399. }
  8400. default:
  8401. // This instruction is not vectorized by simple widening.
  8402. LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
  8403. llvm_unreachable("Unhandled instruction!");
  8404. } // end of switch.
  8405. }
  8406. void VPWidenGEPRecipe::execute(VPTransformState &State) {
  8407. auto *GEP = cast<GetElementPtrInst>(getUnderlyingInstr());
  8408. // Construct a vector GEP by widening the operands of the scalar GEP as
  8409. // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
  8410. // results in a vector of pointers when at least one operand of the GEP
  8411. // is vector-typed. Thus, to keep the representation compact, we only use
  8412. // vector-typed operands for loop-varying values.
  8413. if (State.VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
  8414. // If we are vectorizing, but the GEP has only loop-invariant operands,
  8415. // the GEP we build (by only using vector-typed operands for
  8416. // loop-varying values) would be a scalar pointer. Thus, to ensure we
  8417. // produce a vector of pointers, we need to either arbitrarily pick an
  8418. // operand to broadcast, or broadcast a clone of the original GEP.
  8419. // Here, we broadcast a clone of the original.
  8420. //
  8421. // TODO: If at some point we decide to scalarize instructions having
  8422. // loop-invariant operands, this special case will no longer be
  8423. // required. We would add the scalarization decision to
  8424. // collectLoopScalars() and teach getVectorValue() to broadcast
  8425. // the lane-zero scalar value.
  8426. auto *Clone = State.Builder.Insert(GEP->clone());
  8427. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8428. Value *EntryPart = State.Builder.CreateVectorSplat(State.VF, Clone);
  8429. State.set(this, EntryPart, Part);
  8430. State.ILV->addMetadata(EntryPart, GEP);
  8431. }
  8432. } else {
  8433. // If the GEP has at least one loop-varying operand, we are sure to
  8434. // produce a vector of pointers. But if we are only unrolling, we want
  8435. // to produce a scalar GEP for each unroll part. Thus, the GEP we
  8436. // produce with the code below will be scalar (if VF == 1) or vector
  8437. // (otherwise). Note that for the unroll-only case, we still maintain
  8438. // values in the vector mapping with initVector, as we do for other
  8439. // instructions.
  8440. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8441. // The pointer operand of the new GEP. If it's loop-invariant, we
  8442. // won't broadcast it.
  8443. auto *Ptr = IsPtrLoopInvariant
  8444. ? State.get(getOperand(0), VPIteration(0, 0))
  8445. : State.get(getOperand(0), Part);
  8446. // Collect all the indices for the new GEP. If any index is
  8447. // loop-invariant, we won't broadcast it.
  8448. SmallVector<Value *, 4> Indices;
  8449. for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
  8450. VPValue *Operand = getOperand(I);
  8451. if (IsIndexLoopInvariant[I - 1])
  8452. Indices.push_back(State.get(Operand, VPIteration(0, 0)));
  8453. else
  8454. Indices.push_back(State.get(Operand, Part));
  8455. }
  8456. // If the GEP instruction is vectorized and was in a basic block that
  8457. // needed predication, we can't propagate the poison-generating 'inbounds'
  8458. // flag. The control flow has been linearized and the GEP is no longer
  8459. // guarded by the predicate, which could make the 'inbounds' properties to
  8460. // no longer hold.
  8461. bool IsInBounds =
  8462. GEP->isInBounds() && State.MayGeneratePoisonRecipes.count(this) == 0;
  8463. // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
  8464. // but it should be a vector, otherwise.
  8465. auto *NewGEP = IsInBounds
  8466. ? State.Builder.CreateInBoundsGEP(
  8467. GEP->getSourceElementType(), Ptr, Indices)
  8468. : State.Builder.CreateGEP(GEP->getSourceElementType(),
  8469. Ptr, Indices);
  8470. assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
  8471. "NewGEP is not a pointer vector");
  8472. State.set(this, NewGEP, Part);
  8473. State.ILV->addMetadata(NewGEP, GEP);
  8474. }
  8475. }
  8476. }
  8477. void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
  8478. assert(!State.Instance && "Int or FP induction being replicated.");
  8479. auto *CanonicalIV = State.get(getParent()->getPlan()->getCanonicalIV(), 0);
  8480. State.ILV->widenIntOrFpInduction(IV, this, State, CanonicalIV);
  8481. }
  8482. void VPWidenPHIRecipe::execute(VPTransformState &State) {
  8483. State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
  8484. State);
  8485. }
  8486. void VPBlendRecipe::execute(VPTransformState &State) {
  8487. State.ILV->setDebugLocFromInst(Phi, &State.Builder);
  8488. // We know that all PHIs in non-header blocks are converted into
  8489. // selects, so we don't have to worry about the insertion order and we
  8490. // can just use the builder.
  8491. // At this point we generate the predication tree. There may be
  8492. // duplications since this is a simple recursive scan, but future
  8493. // optimizations will clean it up.
  8494. unsigned NumIncoming = getNumIncomingValues();
  8495. // Generate a sequence of selects of the form:
  8496. // SELECT(Mask3, In3,
  8497. // SELECT(Mask2, In2,
  8498. // SELECT(Mask1, In1,
  8499. // In0)))
  8500. // Note that Mask0 is never used: lanes for which no path reaches this phi and
  8501. // are essentially undef are taken from In0.
  8502. InnerLoopVectorizer::VectorParts Entry(State.UF);
  8503. for (unsigned In = 0; In < NumIncoming; ++In) {
  8504. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8505. // We might have single edge PHIs (blocks) - use an identity
  8506. // 'select' for the first PHI operand.
  8507. Value *In0 = State.get(getIncomingValue(In), Part);
  8508. if (In == 0)
  8509. Entry[Part] = In0; // Initialize with the first incoming value.
  8510. else {
  8511. // Select between the current value and the previous incoming edge
  8512. // based on the incoming mask.
  8513. Value *Cond = State.get(getMask(In), Part);
  8514. Entry[Part] =
  8515. State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
  8516. }
  8517. }
  8518. }
  8519. for (unsigned Part = 0; Part < State.UF; ++Part)
  8520. State.set(this, Entry[Part], Part);
  8521. }
  8522. void VPInterleaveRecipe::execute(VPTransformState &State) {
  8523. assert(!State.Instance && "Interleave group being replicated.");
  8524. State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
  8525. getStoredValues(), getMask());
  8526. }
  8527. void VPReductionRecipe::execute(VPTransformState &State) {
  8528. assert(!State.Instance && "Reduction being replicated.");
  8529. Value *PrevInChain = State.get(getChainOp(), 0);
  8530. RecurKind Kind = RdxDesc->getRecurrenceKind();
  8531. bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
  8532. // Propagate the fast-math flags carried by the underlying instruction.
  8533. IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
  8534. State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
  8535. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8536. Value *NewVecOp = State.get(getVecOp(), Part);
  8537. if (VPValue *Cond = getCondOp()) {
  8538. Value *NewCond = State.get(Cond, Part);
  8539. VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
  8540. Value *Iden = RdxDesc->getRecurrenceIdentity(
  8541. Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
  8542. Value *IdenVec =
  8543. State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
  8544. Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
  8545. NewVecOp = Select;
  8546. }
  8547. Value *NewRed;
  8548. Value *NextInChain;
  8549. if (IsOrdered) {
  8550. if (State.VF.isVector())
  8551. NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
  8552. PrevInChain);
  8553. else
  8554. NewRed = State.Builder.CreateBinOp(
  8555. (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
  8556. NewVecOp);
  8557. PrevInChain = NewRed;
  8558. } else {
  8559. PrevInChain = State.get(getChainOp(), Part);
  8560. NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
  8561. }
  8562. if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
  8563. NextInChain =
  8564. createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
  8565. NewRed, PrevInChain);
  8566. } else if (IsOrdered)
  8567. NextInChain = NewRed;
  8568. else
  8569. NextInChain = State.Builder.CreateBinOp(
  8570. (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
  8571. PrevInChain);
  8572. State.set(this, NextInChain, Part);
  8573. }
  8574. }
  8575. void VPReplicateRecipe::execute(VPTransformState &State) {
  8576. if (State.Instance) { // Generate a single instance.
  8577. assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
  8578. State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
  8579. IsPredicated, State);
  8580. // Insert scalar instance packing it into a vector.
  8581. if (AlsoPack && State.VF.isVector()) {
  8582. // If we're constructing lane 0, initialize to start from poison.
  8583. if (State.Instance->Lane.isFirstLane()) {
  8584. assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
  8585. Value *Poison = PoisonValue::get(
  8586. VectorType::get(getUnderlyingValue()->getType(), State.VF));
  8587. State.set(this, Poison, State.Instance->Part);
  8588. }
  8589. State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
  8590. }
  8591. return;
  8592. }
  8593. // Generate scalar instances for all VF lanes of all UF parts, unless the
  8594. // instruction is uniform inwhich case generate only the first lane for each
  8595. // of the UF parts.
  8596. unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
  8597. assert((!State.VF.isScalable() || IsUniform) &&
  8598. "Can't scalarize a scalable vector");
  8599. for (unsigned Part = 0; Part < State.UF; ++Part)
  8600. for (unsigned Lane = 0; Lane < EndLane; ++Lane)
  8601. State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
  8602. VPIteration(Part, Lane), IsPredicated,
  8603. State);
  8604. }
  8605. void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
  8606. assert(State.Instance && "Branch on Mask works only on single instance.");
  8607. unsigned Part = State.Instance->Part;
  8608. unsigned Lane = State.Instance->Lane.getKnownLane();
  8609. Value *ConditionBit = nullptr;
  8610. VPValue *BlockInMask = getMask();
  8611. if (BlockInMask) {
  8612. ConditionBit = State.get(BlockInMask, Part);
  8613. if (ConditionBit->getType()->isVectorTy())
  8614. ConditionBit = State.Builder.CreateExtractElement(
  8615. ConditionBit, State.Builder.getInt32(Lane));
  8616. } else // Block in mask is all-one.
  8617. ConditionBit = State.Builder.getTrue();
  8618. // Replace the temporary unreachable terminator with a new conditional branch,
  8619. // whose two destinations will be set later when they are created.
  8620. auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
  8621. assert(isa<UnreachableInst>(CurrentTerminator) &&
  8622. "Expected to replace unreachable terminator with conditional branch.");
  8623. auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
  8624. CondBr->setSuccessor(0, nullptr);
  8625. ReplaceInstWithInst(CurrentTerminator, CondBr);
  8626. }
  8627. void VPPredInstPHIRecipe::execute(VPTransformState &State) {
  8628. assert(State.Instance && "Predicated instruction PHI works per instance.");
  8629. Instruction *ScalarPredInst =
  8630. cast<Instruction>(State.get(getOperand(0), *State.Instance));
  8631. BasicBlock *PredicatedBB = ScalarPredInst->getParent();
  8632. BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
  8633. assert(PredicatingBB && "Predicated block has no single predecessor.");
  8634. assert(isa<VPReplicateRecipe>(getOperand(0)) &&
  8635. "operand must be VPReplicateRecipe");
  8636. // By current pack/unpack logic we need to generate only a single phi node: if
  8637. // a vector value for the predicated instruction exists at this point it means
  8638. // the instruction has vector users only, and a phi for the vector value is
  8639. // needed. In this case the recipe of the predicated instruction is marked to
  8640. // also do that packing, thereby "hoisting" the insert-element sequence.
  8641. // Otherwise, a phi node for the scalar value is needed.
  8642. unsigned Part = State.Instance->Part;
  8643. if (State.hasVectorValue(getOperand(0), Part)) {
  8644. Value *VectorValue = State.get(getOperand(0), Part);
  8645. InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
  8646. PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
  8647. VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
  8648. VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
  8649. if (State.hasVectorValue(this, Part))
  8650. State.reset(this, VPhi, Part);
  8651. else
  8652. State.set(this, VPhi, Part);
  8653. // NOTE: Currently we need to update the value of the operand, so the next
  8654. // predicated iteration inserts its generated value in the correct vector.
  8655. State.reset(getOperand(0), VPhi, Part);
  8656. } else {
  8657. Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
  8658. PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
  8659. Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
  8660. PredicatingBB);
  8661. Phi->addIncoming(ScalarPredInst, PredicatedBB);
  8662. if (State.hasScalarValue(this, *State.Instance))
  8663. State.reset(this, Phi, *State.Instance);
  8664. else
  8665. State.set(this, Phi, *State.Instance);
  8666. // NOTE: Currently we need to update the value of the operand, so the next
  8667. // predicated iteration inserts its generated value in the correct vector.
  8668. State.reset(getOperand(0), Phi, *State.Instance);
  8669. }
  8670. }
  8671. void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
  8672. VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
  8673. // Attempt to issue a wide load.
  8674. LoadInst *LI = dyn_cast<LoadInst>(&Ingredient);
  8675. StoreInst *SI = dyn_cast<StoreInst>(&Ingredient);
  8676. assert((LI || SI) && "Invalid Load/Store instruction");
  8677. assert((!SI || StoredValue) && "No stored value provided for widened store");
  8678. assert((!LI || !StoredValue) && "Stored value provided for widened load");
  8679. Type *ScalarDataTy = getLoadStoreType(&Ingredient);
  8680. auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
  8681. const Align Alignment = getLoadStoreAlignment(&Ingredient);
  8682. bool CreateGatherScatter = !Consecutive;
  8683. auto &Builder = State.Builder;
  8684. InnerLoopVectorizer::VectorParts BlockInMaskParts(State.UF);
  8685. bool isMaskRequired = getMask();
  8686. if (isMaskRequired)
  8687. for (unsigned Part = 0; Part < State.UF; ++Part)
  8688. BlockInMaskParts[Part] = State.get(getMask(), Part);
  8689. const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
  8690. // Calculate the pointer for the specific unroll-part.
  8691. GetElementPtrInst *PartPtr = nullptr;
  8692. bool InBounds = false;
  8693. if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
  8694. InBounds = gep->isInBounds();
  8695. if (Reverse) {
  8696. // If the address is consecutive but reversed, then the
  8697. // wide store needs to start at the last vector element.
  8698. // RunTimeVF = VScale * VF.getKnownMinValue()
  8699. // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
  8700. Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), State.VF);
  8701. // NumElt = -Part * RunTimeVF
  8702. Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
  8703. // LastLane = 1 - RunTimeVF
  8704. Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
  8705. PartPtr =
  8706. cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
  8707. PartPtr->setIsInBounds(InBounds);
  8708. PartPtr = cast<GetElementPtrInst>(
  8709. Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
  8710. PartPtr->setIsInBounds(InBounds);
  8711. if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
  8712. BlockInMaskParts[Part] =
  8713. Builder.CreateVectorReverse(BlockInMaskParts[Part], "reverse");
  8714. } else {
  8715. Value *Increment =
  8716. createStepForVF(Builder, Builder.getInt32Ty(), State.VF, Part);
  8717. PartPtr = cast<GetElementPtrInst>(
  8718. Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
  8719. PartPtr->setIsInBounds(InBounds);
  8720. }
  8721. unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
  8722. return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
  8723. };
  8724. // Handle Stores:
  8725. if (SI) {
  8726. State.ILV->setDebugLocFromInst(SI);
  8727. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8728. Instruction *NewSI = nullptr;
  8729. Value *StoredVal = State.get(StoredValue, Part);
  8730. if (CreateGatherScatter) {
  8731. Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
  8732. Value *VectorGep = State.get(getAddr(), Part);
  8733. NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
  8734. MaskPart);
  8735. } else {
  8736. if (Reverse) {
  8737. // If we store to reverse consecutive memory locations, then we need
  8738. // to reverse the order of elements in the stored value.
  8739. StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
  8740. // We don't want to update the value in the map as it might be used in
  8741. // another expression. So don't call resetVectorValue(StoredVal).
  8742. }
  8743. auto *VecPtr =
  8744. CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
  8745. if (isMaskRequired)
  8746. NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
  8747. BlockInMaskParts[Part]);
  8748. else
  8749. NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
  8750. }
  8751. State.ILV->addMetadata(NewSI, SI);
  8752. }
  8753. return;
  8754. }
  8755. // Handle loads.
  8756. assert(LI && "Must have a load instruction");
  8757. State.ILV->setDebugLocFromInst(LI);
  8758. for (unsigned Part = 0; Part < State.UF; ++Part) {
  8759. Value *NewLI;
  8760. if (CreateGatherScatter) {
  8761. Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
  8762. Value *VectorGep = State.get(getAddr(), Part);
  8763. NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
  8764. nullptr, "wide.masked.gather");
  8765. State.ILV->addMetadata(NewLI, LI);
  8766. } else {
  8767. auto *VecPtr =
  8768. CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
  8769. if (isMaskRequired)
  8770. NewLI = Builder.CreateMaskedLoad(
  8771. DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
  8772. PoisonValue::get(DataTy), "wide.masked.load");
  8773. else
  8774. NewLI =
  8775. Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
  8776. // Add metadata to the load, but setVectorValue to the reverse shuffle.
  8777. State.ILV->addMetadata(NewLI, LI);
  8778. if (Reverse)
  8779. NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
  8780. }
  8781. State.set(this, NewLI, Part);
  8782. }
  8783. }
  8784. // Determine how to lower the scalar epilogue, which depends on 1) optimising
  8785. // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
  8786. // predication, and 4) a TTI hook that analyses whether the loop is suitable
  8787. // for predication.
  8788. static ScalarEpilogueLowering getScalarEpilogueLowering(
  8789. Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
  8790. BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
  8791. AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
  8792. LoopVectorizationLegality &LVL) {
  8793. // 1) OptSize takes precedence over all other options, i.e. if this is set,
  8794. // don't look at hints or options, and don't request a scalar epilogue.
  8795. // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
  8796. // LoopAccessInfo (due to code dependency and not being able to reliably get
  8797. // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
  8798. // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
  8799. // versioning when the vectorization is forced, unlike hasOptSize. So revert
  8800. // back to the old way and vectorize with versioning when forced. See D81345.)
  8801. if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
  8802. PGSOQueryType::IRPass) &&
  8803. Hints.getForce() != LoopVectorizeHints::FK_Enabled))
  8804. return CM_ScalarEpilogueNotAllowedOptSize;
  8805. // 2) If set, obey the directives
  8806. if (PreferPredicateOverEpilogue.getNumOccurrences()) {
  8807. switch (PreferPredicateOverEpilogue) {
  8808. case PreferPredicateTy::ScalarEpilogue:
  8809. return CM_ScalarEpilogueAllowed;
  8810. case PreferPredicateTy::PredicateElseScalarEpilogue:
  8811. return CM_ScalarEpilogueNotNeededUsePredicate;
  8812. case PreferPredicateTy::PredicateOrDontVectorize:
  8813. return CM_ScalarEpilogueNotAllowedUsePredicate;
  8814. };
  8815. }
  8816. // 3) If set, obey the hints
  8817. switch (Hints.getPredicate()) {
  8818. case LoopVectorizeHints::FK_Enabled:
  8819. return CM_ScalarEpilogueNotNeededUsePredicate;
  8820. case LoopVectorizeHints::FK_Disabled:
  8821. return CM_ScalarEpilogueAllowed;
  8822. };
  8823. // 4) if the TTI hook indicates this is profitable, request predication.
  8824. if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
  8825. LVL.getLAI()))
  8826. return CM_ScalarEpilogueNotNeededUsePredicate;
  8827. return CM_ScalarEpilogueAllowed;
  8828. }
  8829. Value *VPTransformState::get(VPValue *Def, unsigned Part) {
  8830. // If Values have been set for this Def return the one relevant for \p Part.
  8831. if (hasVectorValue(Def, Part))
  8832. return Data.PerPartOutput[Def][Part];
  8833. if (!hasScalarValue(Def, {Part, 0})) {
  8834. Value *IRV = Def->getLiveInIRValue();
  8835. Value *B = ILV->getBroadcastInstrs(IRV);
  8836. set(Def, B, Part);
  8837. return B;
  8838. }
  8839. Value *ScalarValue = get(Def, {Part, 0});
  8840. // If we aren't vectorizing, we can just copy the scalar map values over
  8841. // to the vector map.
  8842. if (VF.isScalar()) {
  8843. set(Def, ScalarValue, Part);
  8844. return ScalarValue;
  8845. }
  8846. auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
  8847. bool IsUniform = RepR && RepR->isUniform();
  8848. unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
  8849. // Check if there is a scalar value for the selected lane.
  8850. if (!hasScalarValue(Def, {Part, LastLane})) {
  8851. // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
  8852. assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
  8853. "unexpected recipe found to be invariant");
  8854. IsUniform = true;
  8855. LastLane = 0;
  8856. }
  8857. auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
  8858. // Set the insert point after the last scalarized instruction or after the
  8859. // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
  8860. // will directly follow the scalar definitions.
  8861. auto OldIP = Builder.saveIP();
  8862. auto NewIP =
  8863. isa<PHINode>(LastInst)
  8864. ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
  8865. : std::next(BasicBlock::iterator(LastInst));
  8866. Builder.SetInsertPoint(&*NewIP);
  8867. // However, if we are vectorizing, we need to construct the vector values.
  8868. // If the value is known to be uniform after vectorization, we can just
  8869. // broadcast the scalar value corresponding to lane zero for each unroll
  8870. // iteration. Otherwise, we construct the vector values using
  8871. // insertelement instructions. Since the resulting vectors are stored in
  8872. // State, we will only generate the insertelements once.
  8873. Value *VectorValue = nullptr;
  8874. if (IsUniform) {
  8875. VectorValue = ILV->getBroadcastInstrs(ScalarValue);
  8876. set(Def, VectorValue, Part);
  8877. } else {
  8878. // Initialize packing with insertelements to start from undef.
  8879. assert(!VF.isScalable() && "VF is assumed to be non scalable.");
  8880. Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
  8881. set(Def, Undef, Part);
  8882. for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
  8883. ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
  8884. VectorValue = get(Def, Part);
  8885. }
  8886. Builder.restoreIP(OldIP);
  8887. return VectorValue;
  8888. }
  8889. // Process the loop in the VPlan-native vectorization path. This path builds
  8890. // VPlan upfront in the vectorization pipeline, which allows to apply
  8891. // VPlan-to-VPlan transformations from the very beginning without modifying the
  8892. // input LLVM IR.
  8893. static bool processLoopInVPlanNativePath(
  8894. Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
  8895. LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
  8896. TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
  8897. OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
  8898. ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
  8899. LoopVectorizationRequirements &Requirements) {
  8900. if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
  8901. LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
  8902. return false;
  8903. }
  8904. assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
  8905. Function *F = L->getHeader()->getParent();
  8906. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
  8907. ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
  8908. F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
  8909. LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
  8910. &Hints, IAI);
  8911. // Use the planner for outer loop vectorization.
  8912. // TODO: CM is not used at this point inside the planner. Turn CM into an
  8913. // optional argument if we don't need it in the future.
  8914. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
  8915. Requirements, ORE);
  8916. // Get user vectorization factor.
  8917. ElementCount UserVF = Hints.getWidth();
  8918. CM.collectElementTypesForWidening();
  8919. // Plan how to best vectorize, return the best VF and its cost.
  8920. const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
  8921. // If we are stress testing VPlan builds, do not attempt to generate vector
  8922. // code. Masked vector code generation support will follow soon.
  8923. // Also, do not attempt to vectorize if no vector code will be produced.
  8924. if (VPlanBuildStressTest || EnableVPlanPredication ||
  8925. VectorizationFactor::Disabled() == VF)
  8926. return false;
  8927. VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
  8928. {
  8929. GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
  8930. F->getParent()->getDataLayout());
  8931. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
  8932. &CM, BFI, PSI, Checks);
  8933. LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
  8934. << L->getHeader()->getParent()->getName() << "\"\n");
  8935. LVP.executePlan(VF.Width, 1, BestPlan, LB, DT);
  8936. }
  8937. // Mark the loop as already vectorized to avoid vectorizing again.
  8938. Hints.setAlreadyVectorized();
  8939. assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
  8940. return true;
  8941. }
  8942. // Emit a remark if there are stores to floats that required a floating point
  8943. // extension. If the vectorized loop was generated with floating point there
  8944. // will be a performance penalty from the conversion overhead and the change in
  8945. // the vector width.
  8946. static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
  8947. SmallVector<Instruction *, 4> Worklist;
  8948. for (BasicBlock *BB : L->getBlocks()) {
  8949. for (Instruction &Inst : *BB) {
  8950. if (auto *S = dyn_cast<StoreInst>(&Inst)) {
  8951. if (S->getValueOperand()->getType()->isFloatTy())
  8952. Worklist.push_back(S);
  8953. }
  8954. }
  8955. }
  8956. // Traverse the floating point stores upwards searching, for floating point
  8957. // conversions.
  8958. SmallPtrSet<const Instruction *, 4> Visited;
  8959. SmallPtrSet<const Instruction *, 4> EmittedRemark;
  8960. while (!Worklist.empty()) {
  8961. auto *I = Worklist.pop_back_val();
  8962. if (!L->contains(I))
  8963. continue;
  8964. if (!Visited.insert(I).second)
  8965. continue;
  8966. // Emit a remark if the floating point store required a floating
  8967. // point conversion.
  8968. // TODO: More work could be done to identify the root cause such as a
  8969. // constant or a function return type and point the user to it.
  8970. if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
  8971. ORE->emit([&]() {
  8972. return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
  8973. I->getDebugLoc(), L->getHeader())
  8974. << "floating point conversion changes vector width. "
  8975. << "Mixed floating point precision requires an up/down "
  8976. << "cast that will negatively impact performance.";
  8977. });
  8978. for (Use &Op : I->operands())
  8979. if (auto *OpI = dyn_cast<Instruction>(Op))
  8980. Worklist.push_back(OpI);
  8981. }
  8982. }
  8983. LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
  8984. : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
  8985. !EnableLoopInterleaving),
  8986. VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
  8987. !EnableLoopVectorization) {}
  8988. bool LoopVectorizePass::processLoop(Loop *L) {
  8989. assert((EnableVPlanNativePath || L->isInnermost()) &&
  8990. "VPlan-native path is not enabled. Only process inner loops.");
  8991. #ifndef NDEBUG
  8992. const std::string DebugLocStr = getDebugLocString(L);
  8993. #endif /* NDEBUG */
  8994. LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
  8995. << L->getHeader()->getParent()->getName() << "\" from "
  8996. << DebugLocStr << "\n");
  8997. LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
  8998. LLVM_DEBUG(
  8999. dbgs() << "LV: Loop hints:"
  9000. << " force="
  9001. << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
  9002. ? "disabled"
  9003. : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
  9004. ? "enabled"
  9005. : "?"))
  9006. << " width=" << Hints.getWidth()
  9007. << " interleave=" << Hints.getInterleave() << "\n");
  9008. // Function containing loop
  9009. Function *F = L->getHeader()->getParent();
  9010. // Looking at the diagnostic output is the only way to determine if a loop
  9011. // was vectorized (other than looking at the IR or machine code), so it
  9012. // is important to generate an optimization remark for each loop. Most of
  9013. // these messages are generated as OptimizationRemarkAnalysis. Remarks
  9014. // generated as OptimizationRemark and OptimizationRemarkMissed are
  9015. // less verbose reporting vectorized loops and unvectorized loops that may
  9016. // benefit from vectorization, respectively.
  9017. if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
  9018. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
  9019. return false;
  9020. }
  9021. PredicatedScalarEvolution PSE(*SE, *L);
  9022. // Check if it is legal to vectorize the loop.
  9023. LoopVectorizationRequirements Requirements;
  9024. LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
  9025. &Requirements, &Hints, DB, AC, BFI, PSI);
  9026. if (!LVL.canVectorize(EnableVPlanNativePath)) {
  9027. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
  9028. Hints.emitRemarkWithHints();
  9029. return false;
  9030. }
  9031. // Check the function attributes and profiles to find out if this function
  9032. // should be optimized for size.
  9033. ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
  9034. F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
  9035. // Entrance to the VPlan-native vectorization path. Outer loops are processed
  9036. // here. They may require CFG and instruction level transformations before
  9037. // even evaluating whether vectorization is profitable. Since we cannot modify
  9038. // the incoming IR, we need to build VPlan upfront in the vectorization
  9039. // pipeline.
  9040. if (!L->isInnermost())
  9041. return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
  9042. ORE, BFI, PSI, Hints, Requirements);
  9043. assert(L->isInnermost() && "Inner loop expected.");
  9044. // Check the loop for a trip count threshold: vectorize loops with a tiny trip
  9045. // count by optimizing for size, to minimize overheads.
  9046. auto ExpectedTC = getSmallBestKnownTC(*SE, L);
  9047. if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
  9048. LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
  9049. << "This loop is worth vectorizing only if no scalar "
  9050. << "iteration overheads are incurred.");
  9051. if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
  9052. LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
  9053. else {
  9054. LLVM_DEBUG(dbgs() << "\n");
  9055. SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
  9056. }
  9057. }
  9058. // Check the function attributes to see if implicit floats are allowed.
  9059. // FIXME: This check doesn't seem possibly correct -- what if the loop is
  9060. // an integer loop and the vector instructions selected are purely integer
  9061. // vector instructions?
  9062. if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
  9063. reportVectorizationFailure(
  9064. "Can't vectorize when the NoImplicitFloat attribute is used",
  9065. "loop not vectorized due to NoImplicitFloat attribute",
  9066. "NoImplicitFloat", ORE, L);
  9067. Hints.emitRemarkWithHints();
  9068. return false;
  9069. }
  9070. // Check if the target supports potentially unsafe FP vectorization.
  9071. // FIXME: Add a check for the type of safety issue (denormal, signaling)
  9072. // for the target we're vectorizing for, to make sure none of the
  9073. // additional fp-math flags can help.
  9074. if (Hints.isPotentiallyUnsafe() &&
  9075. TTI->isFPVectorizationPotentiallyUnsafe()) {
  9076. reportVectorizationFailure(
  9077. "Potentially unsafe FP op prevents vectorization",
  9078. "loop not vectorized due to unsafe FP support.",
  9079. "UnsafeFP", ORE, L);
  9080. Hints.emitRemarkWithHints();
  9081. return false;
  9082. }
  9083. bool AllowOrderedReductions;
  9084. // If the flag is set, use that instead and override the TTI behaviour.
  9085. if (ForceOrderedReductions.getNumOccurrences() > 0)
  9086. AllowOrderedReductions = ForceOrderedReductions;
  9087. else
  9088. AllowOrderedReductions = TTI->enableOrderedReductions();
  9089. if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
  9090. ORE->emit([&]() {
  9091. auto *ExactFPMathInst = Requirements.getExactFPInst();
  9092. return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
  9093. ExactFPMathInst->getDebugLoc(),
  9094. ExactFPMathInst->getParent())
  9095. << "loop not vectorized: cannot prove it is safe to reorder "
  9096. "floating-point operations";
  9097. });
  9098. LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
  9099. "reorder floating-point operations\n");
  9100. Hints.emitRemarkWithHints();
  9101. return false;
  9102. }
  9103. bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
  9104. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
  9105. // If an override option has been passed in for interleaved accesses, use it.
  9106. if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
  9107. UseInterleaved = EnableInterleavedMemAccesses;
  9108. // Analyze interleaved memory accesses.
  9109. if (UseInterleaved) {
  9110. IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
  9111. }
  9112. // Use the cost model.
  9113. LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
  9114. F, &Hints, IAI);
  9115. CM.collectValuesToIgnore();
  9116. CM.collectElementTypesForWidening();
  9117. // Use the planner for vectorization.
  9118. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
  9119. Requirements, ORE);
  9120. // Get user vectorization factor and interleave count.
  9121. ElementCount UserVF = Hints.getWidth();
  9122. unsigned UserIC = Hints.getInterleave();
  9123. // Plan how to best vectorize, return the best VF and its cost.
  9124. Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
  9125. VectorizationFactor VF = VectorizationFactor::Disabled();
  9126. unsigned IC = 1;
  9127. if (MaybeVF) {
  9128. VF = *MaybeVF;
  9129. // Select the interleave count.
  9130. IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
  9131. }
  9132. // Identify the diagnostic messages that should be produced.
  9133. std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
  9134. bool VectorizeLoop = true, InterleaveLoop = true;
  9135. if (VF.Width.isScalar()) {
  9136. LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
  9137. VecDiagMsg = std::make_pair(
  9138. "VectorizationNotBeneficial",
  9139. "the cost-model indicates that vectorization is not beneficial");
  9140. VectorizeLoop = false;
  9141. }
  9142. if (!MaybeVF && UserIC > 1) {
  9143. // Tell the user interleaving was avoided up-front, despite being explicitly
  9144. // requested.
  9145. LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
  9146. "interleaving should be avoided up front\n");
  9147. IntDiagMsg = std::make_pair(
  9148. "InterleavingAvoided",
  9149. "Ignoring UserIC, because interleaving was avoided up front");
  9150. InterleaveLoop = false;
  9151. } else if (IC == 1 && UserIC <= 1) {
  9152. // Tell the user interleaving is not beneficial.
  9153. LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
  9154. IntDiagMsg = std::make_pair(
  9155. "InterleavingNotBeneficial",
  9156. "the cost-model indicates that interleaving is not beneficial");
  9157. InterleaveLoop = false;
  9158. if (UserIC == 1) {
  9159. IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
  9160. IntDiagMsg.second +=
  9161. " and is explicitly disabled or interleave count is set to 1";
  9162. }
  9163. } else if (IC > 1 && UserIC == 1) {
  9164. // Tell the user interleaving is beneficial, but it explicitly disabled.
  9165. LLVM_DEBUG(
  9166. dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
  9167. IntDiagMsg = std::make_pair(
  9168. "InterleavingBeneficialButDisabled",
  9169. "the cost-model indicates that interleaving is beneficial "
  9170. "but is explicitly disabled or interleave count is set to 1");
  9171. InterleaveLoop = false;
  9172. }
  9173. // Override IC if user provided an interleave count.
  9174. IC = UserIC > 0 ? UserIC : IC;
  9175. // Emit diagnostic messages, if any.
  9176. const char *VAPassName = Hints.vectorizeAnalysisPassName();
  9177. if (!VectorizeLoop && !InterleaveLoop) {
  9178. // Do not vectorize or interleaving the loop.
  9179. ORE->emit([&]() {
  9180. return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
  9181. L->getStartLoc(), L->getHeader())
  9182. << VecDiagMsg.second;
  9183. });
  9184. ORE->emit([&]() {
  9185. return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
  9186. L->getStartLoc(), L->getHeader())
  9187. << IntDiagMsg.second;
  9188. });
  9189. return false;
  9190. } else if (!VectorizeLoop && InterleaveLoop) {
  9191. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  9192. ORE->emit([&]() {
  9193. return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
  9194. L->getStartLoc(), L->getHeader())
  9195. << VecDiagMsg.second;
  9196. });
  9197. } else if (VectorizeLoop && !InterleaveLoop) {
  9198. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  9199. << ") in " << DebugLocStr << '\n');
  9200. ORE->emit([&]() {
  9201. return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
  9202. L->getStartLoc(), L->getHeader())
  9203. << IntDiagMsg.second;
  9204. });
  9205. } else if (VectorizeLoop && InterleaveLoop) {
  9206. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  9207. << ") in " << DebugLocStr << '\n');
  9208. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  9209. }
  9210. bool DisableRuntimeUnroll = false;
  9211. MDNode *OrigLoopID = L->getLoopID();
  9212. {
  9213. // Optimistically generate runtime checks. Drop them if they turn out to not
  9214. // be profitable. Limit the scope of Checks, so the cleanup happens
  9215. // immediately after vector codegeneration is done.
  9216. GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
  9217. F->getParent()->getDataLayout());
  9218. if (!VF.Width.isScalar() || IC > 1)
  9219. Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
  9220. using namespace ore;
  9221. if (!VectorizeLoop) {
  9222. assert(IC > 1 && "interleave count should not be 1 or 0");
  9223. // If we decided that it is not legal to vectorize the loop, then
  9224. // interleave it.
  9225. InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
  9226. &CM, BFI, PSI, Checks);
  9227. VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
  9228. LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT);
  9229. ORE->emit([&]() {
  9230. return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
  9231. L->getHeader())
  9232. << "interleaved loop (interleaved count: "
  9233. << NV("InterleaveCount", IC) << ")";
  9234. });
  9235. } else {
  9236. // If we decided that it is *legal* to vectorize the loop, then do it.
  9237. // Consider vectorizing the epilogue too if it's profitable.
  9238. VectorizationFactor EpilogueVF =
  9239. CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
  9240. if (EpilogueVF.Width.isVector()) {
  9241. // The first pass vectorizes the main loop and creates a scalar epilogue
  9242. // to be vectorized by executing the plan (potentially with a different
  9243. // factor) again shortly afterwards.
  9244. EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
  9245. EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
  9246. EPI, &LVL, &CM, BFI, PSI, Checks);
  9247. VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
  9248. LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
  9249. DT);
  9250. ++LoopsVectorized;
  9251. simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
  9252. formLCSSARecursively(*L, *DT, LI, SE);
  9253. // Second pass vectorizes the epilogue and adjusts the control flow
  9254. // edges from the first pass.
  9255. EPI.MainLoopVF = EPI.EpilogueVF;
  9256. EPI.MainLoopUF = EPI.EpilogueUF;
  9257. EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
  9258. ORE, EPI, &LVL, &CM, BFI, PSI,
  9259. Checks);
  9260. VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
  9261. // Ensure that the start values for any VPReductionPHIRecipes are
  9262. // updated before vectorising the epilogue loop.
  9263. VPBasicBlock *Header = BestEpiPlan.getEntry()->getEntryBasicBlock();
  9264. for (VPRecipeBase &R : Header->phis()) {
  9265. if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
  9266. if (auto *Resume = MainILV.getReductionResumeValue(
  9267. ReductionPhi->getRecurrenceDescriptor())) {
  9268. VPValue *StartVal = new VPValue(Resume);
  9269. BestEpiPlan.addExternalDef(StartVal);
  9270. ReductionPhi->setOperand(0, StartVal);
  9271. }
  9272. }
  9273. }
  9274. LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
  9275. DT);
  9276. ++LoopsEpilogueVectorized;
  9277. if (!MainILV.areSafetyChecksAdded())
  9278. DisableRuntimeUnroll = true;
  9279. } else {
  9280. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
  9281. &LVL, &CM, BFI, PSI, Checks);
  9282. VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
  9283. LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
  9284. ++LoopsVectorized;
  9285. // Add metadata to disable runtime unrolling a scalar loop when there
  9286. // are no runtime checks about strides and memory. A scalar loop that is
  9287. // rarely used is not worth unrolling.
  9288. if (!LB.areSafetyChecksAdded())
  9289. DisableRuntimeUnroll = true;
  9290. }
  9291. // Report the vectorization decision.
  9292. ORE->emit([&]() {
  9293. return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
  9294. L->getHeader())
  9295. << "vectorized loop (vectorization width: "
  9296. << NV("VectorizationFactor", VF.Width)
  9297. << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
  9298. });
  9299. }
  9300. if (ORE->allowExtraAnalysis(LV_NAME))
  9301. checkMixedPrecision(L, ORE);
  9302. }
  9303. Optional<MDNode *> RemainderLoopID =
  9304. makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
  9305. LLVMLoopVectorizeFollowupEpilogue});
  9306. if (RemainderLoopID.hasValue()) {
  9307. L->setLoopID(RemainderLoopID.getValue());
  9308. } else {
  9309. if (DisableRuntimeUnroll)
  9310. AddRuntimeUnrollDisableMetaData(L);
  9311. // Mark the loop as already vectorized to avoid vectorizing again.
  9312. Hints.setAlreadyVectorized();
  9313. }
  9314. assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
  9315. return true;
  9316. }
  9317. LoopVectorizeResult LoopVectorizePass::runImpl(
  9318. Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
  9319. DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
  9320. DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
  9321. std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
  9322. OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
  9323. SE = &SE_;
  9324. LI = &LI_;
  9325. TTI = &TTI_;
  9326. DT = &DT_;
  9327. BFI = &BFI_;
  9328. TLI = TLI_;
  9329. AA = &AA_;
  9330. AC = &AC_;
  9331. GetLAA = &GetLAA_;
  9332. DB = &DB_;
  9333. ORE = &ORE_;
  9334. PSI = PSI_;
  9335. // Don't attempt if
  9336. // 1. the target claims to have no vector registers, and
  9337. // 2. interleaving won't help ILP.
  9338. //
  9339. // The second condition is necessary because, even if the target has no
  9340. // vector registers, loop vectorization may still enable scalar
  9341. // interleaving.
  9342. if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
  9343. TTI->getMaxInterleaveFactor(1) < 2)
  9344. return LoopVectorizeResult(false, false);
  9345. bool Changed = false, CFGChanged = false;
  9346. // The vectorizer requires loops to be in simplified form.
  9347. // Since simplification may add new inner loops, it has to run before the
  9348. // legality and profitability checks. This means running the loop vectorizer
  9349. // will simplify all loops, regardless of whether anything end up being
  9350. // vectorized.
  9351. for (auto &L : *LI)
  9352. Changed |= CFGChanged |=
  9353. simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
  9354. // Build up a worklist of inner-loops to vectorize. This is necessary as
  9355. // the act of vectorizing or partially unrolling a loop creates new loops
  9356. // and can invalidate iterators across the loops.
  9357. SmallVector<Loop *, 8> Worklist;
  9358. for (Loop *L : *LI)
  9359. collectSupportedLoops(*L, LI, ORE, Worklist);
  9360. LoopsAnalyzed += Worklist.size();
  9361. // Now walk the identified inner loops.
  9362. while (!Worklist.empty()) {
  9363. Loop *L = Worklist.pop_back_val();
  9364. // For the inner loops we actually process, form LCSSA to simplify the
  9365. // transform.
  9366. Changed |= formLCSSARecursively(*L, *DT, LI, SE);
  9367. Changed |= CFGChanged |= processLoop(L);
  9368. }
  9369. // Process each loop nest in the function.
  9370. return LoopVectorizeResult(Changed, CFGChanged);
  9371. }
  9372. PreservedAnalyses LoopVectorizePass::run(Function &F,
  9373. FunctionAnalysisManager &AM) {
  9374. auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  9375. auto &LI = AM.getResult<LoopAnalysis>(F);
  9376. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  9377. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  9378. auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
  9379. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  9380. auto &AA = AM.getResult<AAManager>(F);
  9381. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  9382. auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
  9383. auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  9384. auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
  9385. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  9386. [&](Loop &L) -> const LoopAccessInfo & {
  9387. LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE,
  9388. TLI, TTI, nullptr, nullptr, nullptr};
  9389. return LAM.getResult<LoopAccessAnalysis>(L, AR);
  9390. };
  9391. auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
  9392. ProfileSummaryInfo *PSI =
  9393. MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
  9394. LoopVectorizeResult Result =
  9395. runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
  9396. if (!Result.MadeAnyChange)
  9397. return PreservedAnalyses::all();
  9398. PreservedAnalyses PA;
  9399. // We currently do not preserve loopinfo/dominator analyses with outer loop
  9400. // vectorization. Until this is addressed, mark these analyses as preserved
  9401. // only for non-VPlan-native path.
  9402. // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
  9403. if (!EnableVPlanNativePath) {
  9404. PA.preserve<LoopAnalysis>();
  9405. PA.preserve<DominatorTreeAnalysis>();
  9406. }
  9407. if (Result.MadeCFGChange) {
  9408. // Making CFG changes likely means a loop got vectorized. Indicate that
  9409. // extra simplification passes should be run.
  9410. // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
  9411. // be run if runtime checks have been added.
  9412. AM.getResult<ShouldRunExtraVectorPasses>(F);
  9413. PA.preserve<ShouldRunExtraVectorPasses>();
  9414. } else {
  9415. PA.preserveSet<CFGAnalyses>();
  9416. }
  9417. return PA;
  9418. }
  9419. void LoopVectorizePass::printPipeline(
  9420. raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
  9421. static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
  9422. OS, MapClassName2PassName);
  9423. OS << "<";
  9424. OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
  9425. OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
  9426. OS << ">";
  9427. }