LoopVectorize.cpp 199 KB

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