LoopVectorize.cpp 211 KB

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