LoopVectorize.cpp 323 KB

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