LoopVectorize.cpp 310 KB

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