LoopVectorize.cpp 194 KB

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