LoopVectorize.cpp 209 KB

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