SLPVectorizer.cpp 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945
  1. //===- SLPVectorizer.cpp - A bottom up SLP 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. // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
  10. // stores that can be put together into vector-stores. Next, it attempts to
  11. // construct vectorizable tree using the use-def chains. If a profitable tree
  12. // was found, the SLP vectorizer performs vectorization on the tree.
  13. //
  14. // The pass is inspired by the work described in the paper:
  15. // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/PostOrderIterator.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/CodeMetrics.h"
  24. #include "llvm/Analysis/GlobalsModRef.h"
  25. #include "llvm/Analysis/LoopAccessAnalysis.h"
  26. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  27. #include "llvm/Analysis/ValueTracking.h"
  28. #include "llvm/Analysis/VectorUtils.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/Dominators.h"
  31. #include "llvm/IR/IRBuilder.h"
  32. #include "llvm/IR/Instructions.h"
  33. #include "llvm/IR/IntrinsicInst.h"
  34. #include "llvm/IR/Module.h"
  35. #include "llvm/IR/NoFolder.h"
  36. #include "llvm/IR/Type.h"
  37. #include "llvm/IR/Value.h"
  38. #include "llvm/IR/Verifier.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Transforms/Vectorize.h"
  44. #include <algorithm>
  45. #include <memory>
  46. using namespace llvm;
  47. using namespace slpvectorizer;
  48. #define SV_NAME "slp-vectorizer"
  49. #define DEBUG_TYPE "SLP"
  50. STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
  51. static cl::opt<int>
  52. SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
  53. cl::desc("Only vectorize if you gain more than this "
  54. "number "));
  55. static cl::opt<bool>
  56. ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
  57. cl::desc("Attempt to vectorize horizontal reductions"));
  58. static cl::opt<bool> ShouldStartVectorizeHorAtStore(
  59. "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
  60. cl::desc(
  61. "Attempt to vectorize horizontal reductions feeding into a store"));
  62. static cl::opt<int>
  63. MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
  64. cl::desc("Attempt to vectorize for this register size in bits"));
  65. /// Limits the size of scheduling regions in a block.
  66. /// It avoid long compile times for _very_ large blocks where vector
  67. /// instructions are spread over a wide range.
  68. /// This limit is way higher than needed by real-world functions.
  69. static cl::opt<int>
  70. ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
  71. cl::desc("Limit the size of the SLP scheduling region per block"));
  72. static cl::opt<int> MinVectorRegSizeOption(
  73. "slp-min-reg-size", cl::init(128), cl::Hidden,
  74. cl::desc("Attempt to vectorize for this register size in bits"));
  75. static cl::opt<unsigned> RecursionMaxDepth(
  76. "slp-recursion-max-depth", cl::init(12), cl::Hidden,
  77. cl::desc("Limit the recursion depth when building a vectorizable tree"));
  78. static cl::opt<unsigned> MinTreeSize(
  79. "slp-min-tree-size", cl::init(3), cl::Hidden,
  80. cl::desc("Only vectorize small trees if they are fully vectorizable"));
  81. // Limit the number of alias checks. The limit is chosen so that
  82. // it has no negative effect on the llvm benchmarks.
  83. static const unsigned AliasedCheckLimit = 10;
  84. // Another limit for the alias checks: The maximum distance between load/store
  85. // instructions where alias checks are done.
  86. // This limit is useful for very large basic blocks.
  87. static const unsigned MaxMemDepDistance = 160;
  88. /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
  89. /// regions to be handled.
  90. static const int MinScheduleRegionSize = 16;
  91. /// \brief Predicate for the element types that the SLP vectorizer supports.
  92. ///
  93. /// The most important thing to filter here are types which are invalid in LLVM
  94. /// vectors. We also filter target specific types which have absolutely no
  95. /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
  96. /// avoids spending time checking the cost model and realizing that they will
  97. /// be inevitably scalarized.
  98. static bool isValidElementType(Type *Ty) {
  99. return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
  100. !Ty->isPPC_FP128Ty();
  101. }
  102. /// \returns true if all of the instructions in \p VL are in the same block or
  103. /// false otherwise.
  104. static bool allSameBlock(ArrayRef<Value *> VL) {
  105. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  106. if (!I0)
  107. return false;
  108. BasicBlock *BB = I0->getParent();
  109. for (int i = 1, e = VL.size(); i < e; i++) {
  110. Instruction *I = dyn_cast<Instruction>(VL[i]);
  111. if (!I)
  112. return false;
  113. if (BB != I->getParent())
  114. return false;
  115. }
  116. return true;
  117. }
  118. /// \returns True if all of the values in \p VL are constants.
  119. static bool allConstant(ArrayRef<Value *> VL) {
  120. for (Value *i : VL)
  121. if (!isa<Constant>(i))
  122. return false;
  123. return true;
  124. }
  125. /// \returns True if all of the values in \p VL are identical.
  126. static bool isSplat(ArrayRef<Value *> VL) {
  127. for (unsigned i = 1, e = VL.size(); i < e; ++i)
  128. if (VL[i] != VL[0])
  129. return false;
  130. return true;
  131. }
  132. ///\returns Opcode that can be clubbed with \p Op to create an alternate
  133. /// sequence which can later be merged as a ShuffleVector instruction.
  134. static unsigned getAltOpcode(unsigned Op) {
  135. switch (Op) {
  136. case Instruction::FAdd:
  137. return Instruction::FSub;
  138. case Instruction::FSub:
  139. return Instruction::FAdd;
  140. case Instruction::Add:
  141. return Instruction::Sub;
  142. case Instruction::Sub:
  143. return Instruction::Add;
  144. default:
  145. return 0;
  146. }
  147. }
  148. ///\returns bool representing if Opcode \p Op can be part
  149. /// of an alternate sequence which can later be merged as
  150. /// a ShuffleVector instruction.
  151. static bool canCombineAsAltInst(unsigned Op) {
  152. return Op == Instruction::FAdd || Op == Instruction::FSub ||
  153. Op == Instruction::Sub || Op == Instruction::Add;
  154. }
  155. /// \returns ShuffleVector instruction if instructions in \p VL have
  156. /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
  157. /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
  158. static unsigned isAltInst(ArrayRef<Value *> VL) {
  159. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  160. unsigned Opcode = I0->getOpcode();
  161. unsigned AltOpcode = getAltOpcode(Opcode);
  162. for (int i = 1, e = VL.size(); i < e; i++) {
  163. Instruction *I = dyn_cast<Instruction>(VL[i]);
  164. if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
  165. return 0;
  166. }
  167. return Instruction::ShuffleVector;
  168. }
  169. /// \returns The opcode if all of the Instructions in \p VL have the same
  170. /// opcode, or zero.
  171. static unsigned getSameOpcode(ArrayRef<Value *> VL) {
  172. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  173. if (!I0)
  174. return 0;
  175. unsigned Opcode = I0->getOpcode();
  176. for (int i = 1, e = VL.size(); i < e; i++) {
  177. Instruction *I = dyn_cast<Instruction>(VL[i]);
  178. if (!I || Opcode != I->getOpcode()) {
  179. if (canCombineAsAltInst(Opcode) && i == 1)
  180. return isAltInst(VL);
  181. return 0;
  182. }
  183. }
  184. return Opcode;
  185. }
  186. /// Get the intersection (logical and) of all of the potential IR flags
  187. /// of each scalar operation (VL) that will be converted into a vector (I).
  188. /// Flag set: NSW, NUW, exact, and all of fast-math.
  189. static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
  190. if (auto *VecOp = dyn_cast<Instruction>(I)) {
  191. if (auto *Intersection = dyn_cast<Instruction>(VL[0])) {
  192. // Intersection is initialized to the 0th scalar,
  193. // so start counting from index '1'.
  194. for (int i = 1, e = VL.size(); i < e; ++i) {
  195. if (auto *Scalar = dyn_cast<Instruction>(VL[i]))
  196. Intersection->andIRFlags(Scalar);
  197. }
  198. VecOp->copyIRFlags(Intersection);
  199. }
  200. }
  201. }
  202. /// \returns true if all of the values in \p VL have the same type or false
  203. /// otherwise.
  204. static bool allSameType(ArrayRef<Value *> VL) {
  205. Type *Ty = VL[0]->getType();
  206. for (int i = 1, e = VL.size(); i < e; i++)
  207. if (VL[i]->getType() != Ty)
  208. return false;
  209. return true;
  210. }
  211. /// \returns True if Extract{Value,Element} instruction extracts element Idx.
  212. static bool matchExtractIndex(Instruction *E, unsigned Idx, unsigned Opcode) {
  213. assert(Opcode == Instruction::ExtractElement ||
  214. Opcode == Instruction::ExtractValue);
  215. if (Opcode == Instruction::ExtractElement) {
  216. ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
  217. return CI && CI->getZExtValue() == Idx;
  218. } else {
  219. ExtractValueInst *EI = cast<ExtractValueInst>(E);
  220. return EI->getNumIndices() == 1 && *EI->idx_begin() == Idx;
  221. }
  222. }
  223. /// \returns True if in-tree use also needs extract. This refers to
  224. /// possible scalar operand in vectorized instruction.
  225. static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
  226. TargetLibraryInfo *TLI) {
  227. unsigned Opcode = UserInst->getOpcode();
  228. switch (Opcode) {
  229. case Instruction::Load: {
  230. LoadInst *LI = cast<LoadInst>(UserInst);
  231. return (LI->getPointerOperand() == Scalar);
  232. }
  233. case Instruction::Store: {
  234. StoreInst *SI = cast<StoreInst>(UserInst);
  235. return (SI->getPointerOperand() == Scalar);
  236. }
  237. case Instruction::Call: {
  238. CallInst *CI = cast<CallInst>(UserInst);
  239. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  240. if (hasVectorInstrinsicScalarOpd(ID, 1)) {
  241. return (CI->getArgOperand(1) == Scalar);
  242. }
  243. }
  244. default:
  245. return false;
  246. }
  247. }
  248. /// \returns the AA location that is being access by the instruction.
  249. static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
  250. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  251. return MemoryLocation::get(SI);
  252. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  253. return MemoryLocation::get(LI);
  254. return MemoryLocation();
  255. }
  256. /// \returns True if the instruction is not a volatile or atomic load/store.
  257. static bool isSimple(Instruction *I) {
  258. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  259. return LI->isSimple();
  260. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  261. return SI->isSimple();
  262. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
  263. return !MI->isVolatile();
  264. return true;
  265. }
  266. namespace llvm {
  267. namespace slpvectorizer {
  268. /// Bottom Up SLP Vectorizer.
  269. class BoUpSLP {
  270. public:
  271. typedef SmallVector<Value *, 8> ValueList;
  272. typedef SmallVector<Instruction *, 16> InstrList;
  273. typedef SmallPtrSet<Value *, 16> ValueSet;
  274. typedef SmallVector<StoreInst *, 8> StoreList;
  275. BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
  276. TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
  277. DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
  278. const DataLayout *DL)
  279. : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
  280. SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), DB(DB),
  281. DL(DL), Builder(Se->getContext()) {
  282. CodeMetrics::collectEphemeralValues(F, AC, EphValues);
  283. // Use the vector register size specified by the target unless overridden
  284. // by a command-line option.
  285. // TODO: It would be better to limit the vectorization factor based on
  286. // data type rather than just register size. For example, x86 AVX has
  287. // 256-bit registers, but it does not support integer operations
  288. // at that width (that requires AVX2).
  289. if (MaxVectorRegSizeOption.getNumOccurrences())
  290. MaxVecRegSize = MaxVectorRegSizeOption;
  291. else
  292. MaxVecRegSize = TTI->getRegisterBitWidth(true);
  293. MinVecRegSize = MinVectorRegSizeOption;
  294. }
  295. /// \brief Vectorize the tree that starts with the elements in \p VL.
  296. /// Returns the vectorized root.
  297. Value *vectorizeTree();
  298. /// \returns the cost incurred by unwanted spills and fills, caused by
  299. /// holding live values over call sites.
  300. int getSpillCost();
  301. /// \returns the vectorization cost of the subtree that starts at \p VL.
  302. /// A negative number means that this is profitable.
  303. int getTreeCost();
  304. /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
  305. /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
  306. void buildTree(ArrayRef<Value *> Roots,
  307. ArrayRef<Value *> UserIgnoreLst = None);
  308. /// Clear the internal data structures that are created by 'buildTree'.
  309. void deleteTree() {
  310. VectorizableTree.clear();
  311. ScalarToTreeEntry.clear();
  312. MustGather.clear();
  313. ExternalUses.clear();
  314. NumLoadsWantToKeepOrder = 0;
  315. NumLoadsWantToChangeOrder = 0;
  316. for (auto &Iter : BlocksSchedules) {
  317. BlockScheduling *BS = Iter.second.get();
  318. BS->clear();
  319. }
  320. MinBWs.clear();
  321. }
  322. /// \brief Perform LICM and CSE on the newly generated gather sequences.
  323. void optimizeGatherSequence();
  324. /// \returns true if it is beneficial to reverse the vector order.
  325. bool shouldReorder() const {
  326. return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
  327. }
  328. /// \return The vector element size in bits to use when vectorizing the
  329. /// expression tree ending at \p V. If V is a store, the size is the width of
  330. /// the stored value. Otherwise, the size is the width of the largest loaded
  331. /// value reaching V. This method is used by the vectorizer to calculate
  332. /// vectorization factors.
  333. unsigned getVectorElementSize(Value *V);
  334. /// Compute the minimum type sizes required to represent the entries in a
  335. /// vectorizable tree.
  336. void computeMinimumValueSizes();
  337. // \returns maximum vector register size as set by TTI or overridden by cl::opt.
  338. unsigned getMaxVecRegSize() const {
  339. return MaxVecRegSize;
  340. }
  341. // \returns minimum vector register size as set by cl::opt.
  342. unsigned getMinVecRegSize() const {
  343. return MinVecRegSize;
  344. }
  345. /// \brief Check if ArrayType or StructType is isomorphic to some VectorType.
  346. ///
  347. /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
  348. unsigned canMapToVector(Type *T, const DataLayout &DL) const;
  349. /// \returns True if the VectorizableTree is both tiny and not fully
  350. /// vectorizable. We do not vectorize such trees.
  351. bool isTreeTinyAndNotFullyVectorizable();
  352. private:
  353. struct TreeEntry;
  354. /// \returns the cost of the vectorizable entry.
  355. int getEntryCost(TreeEntry *E);
  356. /// This is the recursive part of buildTree.
  357. void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
  358. /// \returns True if the ExtractElement/ExtractValue instructions in VL can
  359. /// be vectorized to use the original vector (or aggregate "bitcast" to a vector).
  360. bool canReuseExtract(ArrayRef<Value *> VL, unsigned Opcode) const;
  361. /// Vectorize a single entry in the tree.
  362. Value *vectorizeTree(TreeEntry *E);
  363. /// Vectorize a single entry in the tree, starting in \p VL.
  364. Value *vectorizeTree(ArrayRef<Value *> VL);
  365. /// \returns the pointer to the vectorized value if \p VL is already
  366. /// vectorized, or NULL. They may happen in cycles.
  367. Value *alreadyVectorized(ArrayRef<Value *> VL) const;
  368. /// \returns the scalarization cost for this type. Scalarization in this
  369. /// context means the creation of vectors from a group of scalars.
  370. int getGatherCost(Type *Ty);
  371. /// \returns the scalarization cost for this list of values. Assuming that
  372. /// this subtree gets vectorized, we may need to extract the values from the
  373. /// roots. This method calculates the cost of extracting the values.
  374. int getGatherCost(ArrayRef<Value *> VL);
  375. /// \brief Set the Builder insert point to one after the last instruction in
  376. /// the bundle
  377. void setInsertPointAfterBundle(ArrayRef<Value *> VL);
  378. /// \returns a vector from a collection of scalars in \p VL.
  379. Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
  380. /// \returns whether the VectorizableTree is fully vectorizable and will
  381. /// be beneficial even the tree height is tiny.
  382. bool isFullyVectorizableTinyTree();
  383. /// \reorder commutative operands in alt shuffle if they result in
  384. /// vectorized code.
  385. void reorderAltShuffleOperands(ArrayRef<Value *> VL,
  386. SmallVectorImpl<Value *> &Left,
  387. SmallVectorImpl<Value *> &Right);
  388. /// \reorder commutative operands to get better probability of
  389. /// generating vectorized code.
  390. void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
  391. SmallVectorImpl<Value *> &Left,
  392. SmallVectorImpl<Value *> &Right);
  393. struct TreeEntry {
  394. TreeEntry() : Scalars(), VectorizedValue(nullptr),
  395. NeedToGather(0) {}
  396. /// \returns true if the scalars in VL are equal to this entry.
  397. bool isSame(ArrayRef<Value *> VL) const {
  398. assert(VL.size() == Scalars.size() && "Invalid size");
  399. return std::equal(VL.begin(), VL.end(), Scalars.begin());
  400. }
  401. /// A vector of scalars.
  402. ValueList Scalars;
  403. /// The Scalars are vectorized into this value. It is initialized to Null.
  404. Value *VectorizedValue;
  405. /// Do we need to gather this sequence ?
  406. bool NeedToGather;
  407. };
  408. /// Create a new VectorizableTree entry.
  409. TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
  410. VectorizableTree.emplace_back();
  411. int idx = VectorizableTree.size() - 1;
  412. TreeEntry *Last = &VectorizableTree[idx];
  413. Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
  414. Last->NeedToGather = !Vectorized;
  415. if (Vectorized) {
  416. for (int i = 0, e = VL.size(); i != e; ++i) {
  417. assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
  418. ScalarToTreeEntry[VL[i]] = idx;
  419. }
  420. } else {
  421. MustGather.insert(VL.begin(), VL.end());
  422. }
  423. return Last;
  424. }
  425. /// -- Vectorization State --
  426. /// Holds all of the tree entries.
  427. std::vector<TreeEntry> VectorizableTree;
  428. /// Maps a specific scalar to its tree entry.
  429. SmallDenseMap<Value*, int> ScalarToTreeEntry;
  430. /// A list of scalars that we found that we need to keep as scalars.
  431. ValueSet MustGather;
  432. /// This POD struct describes one external user in the vectorized tree.
  433. struct ExternalUser {
  434. ExternalUser (Value *S, llvm::User *U, int L) :
  435. Scalar(S), User(U), Lane(L){}
  436. // Which scalar in our function.
  437. Value *Scalar;
  438. // Which user that uses the scalar.
  439. llvm::User *User;
  440. // Which lane does the scalar belong to.
  441. int Lane;
  442. };
  443. typedef SmallVector<ExternalUser, 16> UserList;
  444. /// Checks if two instructions may access the same memory.
  445. ///
  446. /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
  447. /// is invariant in the calling loop.
  448. bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
  449. Instruction *Inst2) {
  450. // First check if the result is already in the cache.
  451. AliasCacheKey key = std::make_pair(Inst1, Inst2);
  452. Optional<bool> &result = AliasCache[key];
  453. if (result.hasValue()) {
  454. return result.getValue();
  455. }
  456. MemoryLocation Loc2 = getLocation(Inst2, AA);
  457. bool aliased = true;
  458. if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
  459. // Do the alias check.
  460. aliased = AA->alias(Loc1, Loc2);
  461. }
  462. // Store the result in the cache.
  463. result = aliased;
  464. return aliased;
  465. }
  466. typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
  467. /// Cache for alias results.
  468. /// TODO: consider moving this to the AliasAnalysis itself.
  469. DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
  470. /// Removes an instruction from its block and eventually deletes it.
  471. /// It's like Instruction::eraseFromParent() except that the actual deletion
  472. /// is delayed until BoUpSLP is destructed.
  473. /// This is required to ensure that there are no incorrect collisions in the
  474. /// AliasCache, which can happen if a new instruction is allocated at the
  475. /// same address as a previously deleted instruction.
  476. void eraseInstruction(Instruction *I) {
  477. I->removeFromParent();
  478. I->dropAllReferences();
  479. DeletedInstructions.push_back(std::unique_ptr<Instruction>(I));
  480. }
  481. /// Temporary store for deleted instructions. Instructions will be deleted
  482. /// eventually when the BoUpSLP is destructed.
  483. SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions;
  484. /// A list of values that need to extracted out of the tree.
  485. /// This list holds pairs of (Internal Scalar : External User).
  486. UserList ExternalUses;
  487. /// Values used only by @llvm.assume calls.
  488. SmallPtrSet<const Value *, 32> EphValues;
  489. /// Holds all of the instructions that we gathered.
  490. SetVector<Instruction *> GatherSeq;
  491. /// A list of blocks that we are going to CSE.
  492. SetVector<BasicBlock *> CSEBlocks;
  493. /// Contains all scheduling relevant data for an instruction.
  494. /// A ScheduleData either represents a single instruction or a member of an
  495. /// instruction bundle (= a group of instructions which is combined into a
  496. /// vector instruction).
  497. struct ScheduleData {
  498. // The initial value for the dependency counters. It means that the
  499. // dependencies are not calculated yet.
  500. enum { InvalidDeps = -1 };
  501. ScheduleData()
  502. : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
  503. NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
  504. Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
  505. UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
  506. void init(int BlockSchedulingRegionID) {
  507. FirstInBundle = this;
  508. NextInBundle = nullptr;
  509. NextLoadStore = nullptr;
  510. IsScheduled = false;
  511. SchedulingRegionID = BlockSchedulingRegionID;
  512. UnscheduledDepsInBundle = UnscheduledDeps;
  513. clearDependencies();
  514. }
  515. /// Returns true if the dependency information has been calculated.
  516. bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
  517. /// Returns true for single instructions and for bundle representatives
  518. /// (= the head of a bundle).
  519. bool isSchedulingEntity() const { return FirstInBundle == this; }
  520. /// Returns true if it represents an instruction bundle and not only a
  521. /// single instruction.
  522. bool isPartOfBundle() const {
  523. return NextInBundle != nullptr || FirstInBundle != this;
  524. }
  525. /// Returns true if it is ready for scheduling, i.e. it has no more
  526. /// unscheduled depending instructions/bundles.
  527. bool isReady() const {
  528. assert(isSchedulingEntity() &&
  529. "can't consider non-scheduling entity for ready list");
  530. return UnscheduledDepsInBundle == 0 && !IsScheduled;
  531. }
  532. /// Modifies the number of unscheduled dependencies, also updating it for
  533. /// the whole bundle.
  534. int incrementUnscheduledDeps(int Incr) {
  535. UnscheduledDeps += Incr;
  536. return FirstInBundle->UnscheduledDepsInBundle += Incr;
  537. }
  538. /// Sets the number of unscheduled dependencies to the number of
  539. /// dependencies.
  540. void resetUnscheduledDeps() {
  541. incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
  542. }
  543. /// Clears all dependency information.
  544. void clearDependencies() {
  545. Dependencies = InvalidDeps;
  546. resetUnscheduledDeps();
  547. MemoryDependencies.clear();
  548. }
  549. void dump(raw_ostream &os) const {
  550. if (!isSchedulingEntity()) {
  551. os << "/ " << *Inst;
  552. } else if (NextInBundle) {
  553. os << '[' << *Inst;
  554. ScheduleData *SD = NextInBundle;
  555. while (SD) {
  556. os << ';' << *SD->Inst;
  557. SD = SD->NextInBundle;
  558. }
  559. os << ']';
  560. } else {
  561. os << *Inst;
  562. }
  563. }
  564. Instruction *Inst;
  565. /// Points to the head in an instruction bundle (and always to this for
  566. /// single instructions).
  567. ScheduleData *FirstInBundle;
  568. /// Single linked list of all instructions in a bundle. Null if it is a
  569. /// single instruction.
  570. ScheduleData *NextInBundle;
  571. /// Single linked list of all memory instructions (e.g. load, store, call)
  572. /// in the block - until the end of the scheduling region.
  573. ScheduleData *NextLoadStore;
  574. /// The dependent memory instructions.
  575. /// This list is derived on demand in calculateDependencies().
  576. SmallVector<ScheduleData *, 4> MemoryDependencies;
  577. /// This ScheduleData is in the current scheduling region if this matches
  578. /// the current SchedulingRegionID of BlockScheduling.
  579. int SchedulingRegionID;
  580. /// Used for getting a "good" final ordering of instructions.
  581. int SchedulingPriority;
  582. /// The number of dependencies. Constitutes of the number of users of the
  583. /// instruction plus the number of dependent memory instructions (if any).
  584. /// This value is calculated on demand.
  585. /// If InvalidDeps, the number of dependencies is not calculated yet.
  586. ///
  587. int Dependencies;
  588. /// The number of dependencies minus the number of dependencies of scheduled
  589. /// instructions. As soon as this is zero, the instruction/bundle gets ready
  590. /// for scheduling.
  591. /// Note that this is negative as long as Dependencies is not calculated.
  592. int UnscheduledDeps;
  593. /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
  594. /// single instructions.
  595. int UnscheduledDepsInBundle;
  596. /// True if this instruction is scheduled (or considered as scheduled in the
  597. /// dry-run).
  598. bool IsScheduled;
  599. };
  600. #ifndef NDEBUG
  601. friend inline raw_ostream &operator<<(raw_ostream &os,
  602. const BoUpSLP::ScheduleData &SD) {
  603. SD.dump(os);
  604. return os;
  605. }
  606. #endif
  607. /// Contains all scheduling data for a basic block.
  608. ///
  609. struct BlockScheduling {
  610. BlockScheduling(BasicBlock *BB)
  611. : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
  612. ScheduleStart(nullptr), ScheduleEnd(nullptr),
  613. FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
  614. ScheduleRegionSize(0),
  615. ScheduleRegionSizeLimit(ScheduleRegionSizeBudget),
  616. // Make sure that the initial SchedulingRegionID is greater than the
  617. // initial SchedulingRegionID in ScheduleData (which is 0).
  618. SchedulingRegionID(1) {}
  619. void clear() {
  620. ReadyInsts.clear();
  621. ScheduleStart = nullptr;
  622. ScheduleEnd = nullptr;
  623. FirstLoadStoreInRegion = nullptr;
  624. LastLoadStoreInRegion = nullptr;
  625. // Reduce the maximum schedule region size by the size of the
  626. // previous scheduling run.
  627. ScheduleRegionSizeLimit -= ScheduleRegionSize;
  628. if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
  629. ScheduleRegionSizeLimit = MinScheduleRegionSize;
  630. ScheduleRegionSize = 0;
  631. // Make a new scheduling region, i.e. all existing ScheduleData is not
  632. // in the new region yet.
  633. ++SchedulingRegionID;
  634. }
  635. ScheduleData *getScheduleData(Value *V) {
  636. ScheduleData *SD = ScheduleDataMap[V];
  637. if (SD && SD->SchedulingRegionID == SchedulingRegionID)
  638. return SD;
  639. return nullptr;
  640. }
  641. bool isInSchedulingRegion(ScheduleData *SD) {
  642. return SD->SchedulingRegionID == SchedulingRegionID;
  643. }
  644. /// Marks an instruction as scheduled and puts all dependent ready
  645. /// instructions into the ready-list.
  646. template <typename ReadyListType>
  647. void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
  648. SD->IsScheduled = true;
  649. DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
  650. ScheduleData *BundleMember = SD;
  651. while (BundleMember) {
  652. // Handle the def-use chain dependencies.
  653. for (Use &U : BundleMember->Inst->operands()) {
  654. ScheduleData *OpDef = getScheduleData(U.get());
  655. if (OpDef && OpDef->hasValidDependencies() &&
  656. OpDef->incrementUnscheduledDeps(-1) == 0) {
  657. // There are no more unscheduled dependencies after decrementing,
  658. // so we can put the dependent instruction into the ready list.
  659. ScheduleData *DepBundle = OpDef->FirstInBundle;
  660. assert(!DepBundle->IsScheduled &&
  661. "already scheduled bundle gets ready");
  662. ReadyList.insert(DepBundle);
  663. DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
  664. }
  665. }
  666. // Handle the memory dependencies.
  667. for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
  668. if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
  669. // There are no more unscheduled dependencies after decrementing,
  670. // so we can put the dependent instruction into the ready list.
  671. ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
  672. assert(!DepBundle->IsScheduled &&
  673. "already scheduled bundle gets ready");
  674. ReadyList.insert(DepBundle);
  675. DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
  676. }
  677. }
  678. BundleMember = BundleMember->NextInBundle;
  679. }
  680. }
  681. /// Put all instructions into the ReadyList which are ready for scheduling.
  682. template <typename ReadyListType>
  683. void initialFillReadyList(ReadyListType &ReadyList) {
  684. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  685. ScheduleData *SD = getScheduleData(I);
  686. if (SD->isSchedulingEntity() && SD->isReady()) {
  687. ReadyList.insert(SD);
  688. DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
  689. }
  690. }
  691. }
  692. /// Checks if a bundle of instructions can be scheduled, i.e. has no
  693. /// cyclic dependencies. This is only a dry-run, no instructions are
  694. /// actually moved at this stage.
  695. bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
  696. /// Un-bundles a group of instructions.
  697. void cancelScheduling(ArrayRef<Value *> VL);
  698. /// Extends the scheduling region so that V is inside the region.
  699. /// \returns true if the region size is within the limit.
  700. bool extendSchedulingRegion(Value *V);
  701. /// Initialize the ScheduleData structures for new instructions in the
  702. /// scheduling region.
  703. void initScheduleData(Instruction *FromI, Instruction *ToI,
  704. ScheduleData *PrevLoadStore,
  705. ScheduleData *NextLoadStore);
  706. /// Updates the dependency information of a bundle and of all instructions/
  707. /// bundles which depend on the original bundle.
  708. void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
  709. BoUpSLP *SLP);
  710. /// Sets all instruction in the scheduling region to un-scheduled.
  711. void resetSchedule();
  712. BasicBlock *BB;
  713. /// Simple memory allocation for ScheduleData.
  714. std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
  715. /// The size of a ScheduleData array in ScheduleDataChunks.
  716. int ChunkSize;
  717. /// The allocator position in the current chunk, which is the last entry
  718. /// of ScheduleDataChunks.
  719. int ChunkPos;
  720. /// Attaches ScheduleData to Instruction.
  721. /// Note that the mapping survives during all vectorization iterations, i.e.
  722. /// ScheduleData structures are recycled.
  723. DenseMap<Value *, ScheduleData *> ScheduleDataMap;
  724. struct ReadyList : SmallVector<ScheduleData *, 8> {
  725. void insert(ScheduleData *SD) { push_back(SD); }
  726. };
  727. /// The ready-list for scheduling (only used for the dry-run).
  728. ReadyList ReadyInsts;
  729. /// The first instruction of the scheduling region.
  730. Instruction *ScheduleStart;
  731. /// The first instruction _after_ the scheduling region.
  732. Instruction *ScheduleEnd;
  733. /// The first memory accessing instruction in the scheduling region
  734. /// (can be null).
  735. ScheduleData *FirstLoadStoreInRegion;
  736. /// The last memory accessing instruction in the scheduling region
  737. /// (can be null).
  738. ScheduleData *LastLoadStoreInRegion;
  739. /// The current size of the scheduling region.
  740. int ScheduleRegionSize;
  741. /// The maximum size allowed for the scheduling region.
  742. int ScheduleRegionSizeLimit;
  743. /// The ID of the scheduling region. For a new vectorization iteration this
  744. /// is incremented which "removes" all ScheduleData from the region.
  745. int SchedulingRegionID;
  746. };
  747. /// Attaches the BlockScheduling structures to basic blocks.
  748. MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
  749. /// Performs the "real" scheduling. Done before vectorization is actually
  750. /// performed in a basic block.
  751. void scheduleBlock(BlockScheduling *BS);
  752. /// List of users to ignore during scheduling and that don't need extracting.
  753. ArrayRef<Value *> UserIgnoreList;
  754. // Number of load bundles that contain consecutive loads.
  755. int NumLoadsWantToKeepOrder;
  756. // Number of load bundles that contain consecutive loads in reversed order.
  757. int NumLoadsWantToChangeOrder;
  758. // Analysis and block reference.
  759. Function *F;
  760. ScalarEvolution *SE;
  761. TargetTransformInfo *TTI;
  762. TargetLibraryInfo *TLI;
  763. AliasAnalysis *AA;
  764. LoopInfo *LI;
  765. DominatorTree *DT;
  766. AssumptionCache *AC;
  767. DemandedBits *DB;
  768. const DataLayout *DL;
  769. unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
  770. unsigned MinVecRegSize; // Set by cl::opt (default: 128).
  771. /// Instruction builder to construct the vectorized tree.
  772. IRBuilder<> Builder;
  773. /// A map of scalar integer values to the smallest bit width with which they
  774. /// can legally be represented. The values map to (width, signed) pairs,
  775. /// where "width" indicates the minimum bit width and "signed" is True if the
  776. /// value must be signed-extended, rather than zero-extended, back to its
  777. /// original width.
  778. MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
  779. };
  780. } // end namespace llvm
  781. } // end namespace slpvectorizer
  782. void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
  783. ArrayRef<Value *> UserIgnoreLst) {
  784. deleteTree();
  785. UserIgnoreList = UserIgnoreLst;
  786. if (!allSameType(Roots))
  787. return;
  788. buildTree_rec(Roots, 0);
  789. // Collect the values that we need to extract from the tree.
  790. for (TreeEntry &EIdx : VectorizableTree) {
  791. TreeEntry *Entry = &EIdx;
  792. // For each lane:
  793. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  794. Value *Scalar = Entry->Scalars[Lane];
  795. // No need to handle users of gathered values.
  796. if (Entry->NeedToGather)
  797. continue;
  798. for (User *U : Scalar->users()) {
  799. DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
  800. Instruction *UserInst = dyn_cast<Instruction>(U);
  801. if (!UserInst)
  802. continue;
  803. // Skip in-tree scalars that become vectors
  804. if (ScalarToTreeEntry.count(U)) {
  805. int Idx = ScalarToTreeEntry[U];
  806. TreeEntry *UseEntry = &VectorizableTree[Idx];
  807. Value *UseScalar = UseEntry->Scalars[0];
  808. // Some in-tree scalars will remain as scalar in vectorized
  809. // instructions. If that is the case, the one in Lane 0 will
  810. // be used.
  811. if (UseScalar != U ||
  812. !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
  813. DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
  814. << ".\n");
  815. assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
  816. continue;
  817. }
  818. }
  819. // Ignore users in the user ignore list.
  820. if (is_contained(UserIgnoreList, UserInst))
  821. continue;
  822. DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
  823. Lane << " from " << *Scalar << ".\n");
  824. ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
  825. }
  826. }
  827. }
  828. }
  829. void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
  830. bool isAltShuffle = false;
  831. assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
  832. if (Depth == RecursionMaxDepth) {
  833. DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
  834. newTreeEntry(VL, false);
  835. return;
  836. }
  837. // Don't handle vectors.
  838. if (VL[0]->getType()->isVectorTy()) {
  839. DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
  840. newTreeEntry(VL, false);
  841. return;
  842. }
  843. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  844. if (SI->getValueOperand()->getType()->isVectorTy()) {
  845. DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
  846. newTreeEntry(VL, false);
  847. return;
  848. }
  849. unsigned Opcode = getSameOpcode(VL);
  850. // Check that this shuffle vector refers to the alternate
  851. // sequence of opcodes.
  852. if (Opcode == Instruction::ShuffleVector) {
  853. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  854. unsigned Op = I0->getOpcode();
  855. if (Op != Instruction::ShuffleVector)
  856. isAltShuffle = true;
  857. }
  858. // If all of the operands are identical or constant we have a simple solution.
  859. if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !Opcode) {
  860. DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
  861. newTreeEntry(VL, false);
  862. return;
  863. }
  864. // We now know that this is a vector of instructions of the same type from
  865. // the same block.
  866. // Don't vectorize ephemeral values.
  867. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  868. if (EphValues.count(VL[i])) {
  869. DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
  870. ") is ephemeral.\n");
  871. newTreeEntry(VL, false);
  872. return;
  873. }
  874. }
  875. // Check if this is a duplicate of another entry.
  876. if (ScalarToTreeEntry.count(VL[0])) {
  877. int Idx = ScalarToTreeEntry[VL[0]];
  878. TreeEntry *E = &VectorizableTree[Idx];
  879. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  880. DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
  881. if (E->Scalars[i] != VL[i]) {
  882. DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
  883. newTreeEntry(VL, false);
  884. return;
  885. }
  886. }
  887. DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
  888. return;
  889. }
  890. // Check that none of the instructions in the bundle are already in the tree.
  891. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  892. if (ScalarToTreeEntry.count(VL[i])) {
  893. DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
  894. ") is already in tree.\n");
  895. newTreeEntry(VL, false);
  896. return;
  897. }
  898. }
  899. // If any of the scalars is marked as a value that needs to stay scalar then
  900. // we need to gather the scalars.
  901. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  902. if (MustGather.count(VL[i])) {
  903. DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
  904. newTreeEntry(VL, false);
  905. return;
  906. }
  907. }
  908. // Check that all of the users of the scalars that we want to vectorize are
  909. // schedulable.
  910. Instruction *VL0 = cast<Instruction>(VL[0]);
  911. BasicBlock *BB = cast<Instruction>(VL0)->getParent();
  912. if (!DT->isReachableFromEntry(BB)) {
  913. // Don't go into unreachable blocks. They may contain instructions with
  914. // dependency cycles which confuse the final scheduling.
  915. DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
  916. newTreeEntry(VL, false);
  917. return;
  918. }
  919. // Check that every instructions appears once in this bundle.
  920. for (unsigned i = 0, e = VL.size(); i < e; ++i)
  921. for (unsigned j = i+1; j < e; ++j)
  922. if (VL[i] == VL[j]) {
  923. DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
  924. newTreeEntry(VL, false);
  925. return;
  926. }
  927. auto &BSRef = BlocksSchedules[BB];
  928. if (!BSRef) {
  929. BSRef = llvm::make_unique<BlockScheduling>(BB);
  930. }
  931. BlockScheduling &BS = *BSRef.get();
  932. if (!BS.tryScheduleBundle(VL, this)) {
  933. DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
  934. assert((!BS.getScheduleData(VL[0]) ||
  935. !BS.getScheduleData(VL[0])->isPartOfBundle()) &&
  936. "tryScheduleBundle should cancelScheduling on failure");
  937. newTreeEntry(VL, false);
  938. return;
  939. }
  940. DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
  941. switch (Opcode) {
  942. case Instruction::PHI: {
  943. PHINode *PH = dyn_cast<PHINode>(VL0);
  944. // Check for terminator values (e.g. invoke).
  945. for (unsigned j = 0; j < VL.size(); ++j)
  946. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  947. TerminatorInst *Term = dyn_cast<TerminatorInst>(
  948. cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
  949. if (Term) {
  950. DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
  951. BS.cancelScheduling(VL);
  952. newTreeEntry(VL, false);
  953. return;
  954. }
  955. }
  956. newTreeEntry(VL, true);
  957. DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
  958. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  959. ValueList Operands;
  960. // Prepare the operand vector.
  961. for (Value *j : VL)
  962. Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
  963. PH->getIncomingBlock(i)));
  964. buildTree_rec(Operands, Depth + 1);
  965. }
  966. return;
  967. }
  968. case Instruction::ExtractValue:
  969. case Instruction::ExtractElement: {
  970. bool Reuse = canReuseExtract(VL, Opcode);
  971. if (Reuse) {
  972. DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
  973. } else {
  974. BS.cancelScheduling(VL);
  975. }
  976. newTreeEntry(VL, Reuse);
  977. return;
  978. }
  979. case Instruction::Load: {
  980. // Check that a vectorized load would load the same memory as a scalar
  981. // load.
  982. // For example we don't want vectorize loads that are smaller than 8 bit.
  983. // Even though we have a packed struct {<i2, i2, i2, i2>} LLVM treats
  984. // loading/storing it as an i8 struct. If we vectorize loads/stores from
  985. // such a struct we read/write packed bits disagreeing with the
  986. // unvectorized version.
  987. Type *ScalarTy = VL[0]->getType();
  988. if (DL->getTypeSizeInBits(ScalarTy) !=
  989. DL->getTypeAllocSizeInBits(ScalarTy)) {
  990. BS.cancelScheduling(VL);
  991. newTreeEntry(VL, false);
  992. DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
  993. return;
  994. }
  995. // Make sure all loads in the bundle are simple - we can't vectorize
  996. // atomic or volatile loads.
  997. for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
  998. LoadInst *L = cast<LoadInst>(VL[i]);
  999. if (!L->isSimple()) {
  1000. BS.cancelScheduling(VL);
  1001. newTreeEntry(VL, false);
  1002. DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
  1003. return;
  1004. }
  1005. }
  1006. // Check if the loads are consecutive, reversed, or neither.
  1007. // TODO: What we really want is to sort the loads, but for now, check
  1008. // the two likely directions.
  1009. bool Consecutive = true;
  1010. bool ReverseConsecutive = true;
  1011. for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
  1012. if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
  1013. Consecutive = false;
  1014. break;
  1015. } else {
  1016. ReverseConsecutive = false;
  1017. }
  1018. }
  1019. if (Consecutive) {
  1020. ++NumLoadsWantToKeepOrder;
  1021. newTreeEntry(VL, true);
  1022. DEBUG(dbgs() << "SLP: added a vector of loads.\n");
  1023. return;
  1024. }
  1025. // If none of the load pairs were consecutive when checked in order,
  1026. // check the reverse order.
  1027. if (ReverseConsecutive)
  1028. for (unsigned i = VL.size() - 1; i > 0; --i)
  1029. if (!isConsecutiveAccess(VL[i], VL[i - 1], *DL, *SE)) {
  1030. ReverseConsecutive = false;
  1031. break;
  1032. }
  1033. BS.cancelScheduling(VL);
  1034. newTreeEntry(VL, false);
  1035. if (ReverseConsecutive) {
  1036. ++NumLoadsWantToChangeOrder;
  1037. DEBUG(dbgs() << "SLP: Gathering reversed loads.\n");
  1038. } else {
  1039. DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
  1040. }
  1041. return;
  1042. }
  1043. case Instruction::ZExt:
  1044. case Instruction::SExt:
  1045. case Instruction::FPToUI:
  1046. case Instruction::FPToSI:
  1047. case Instruction::FPExt:
  1048. case Instruction::PtrToInt:
  1049. case Instruction::IntToPtr:
  1050. case Instruction::SIToFP:
  1051. case Instruction::UIToFP:
  1052. case Instruction::Trunc:
  1053. case Instruction::FPTrunc:
  1054. case Instruction::BitCast: {
  1055. Type *SrcTy = VL0->getOperand(0)->getType();
  1056. for (unsigned i = 0; i < VL.size(); ++i) {
  1057. Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
  1058. if (Ty != SrcTy || !isValidElementType(Ty)) {
  1059. BS.cancelScheduling(VL);
  1060. newTreeEntry(VL, false);
  1061. DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
  1062. return;
  1063. }
  1064. }
  1065. newTreeEntry(VL, true);
  1066. DEBUG(dbgs() << "SLP: added a vector of casts.\n");
  1067. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  1068. ValueList Operands;
  1069. // Prepare the operand vector.
  1070. for (Value *j : VL)
  1071. Operands.push_back(cast<Instruction>(j)->getOperand(i));
  1072. buildTree_rec(Operands, Depth+1);
  1073. }
  1074. return;
  1075. }
  1076. case Instruction::ICmp:
  1077. case Instruction::FCmp: {
  1078. // Check that all of the compares have the same predicate.
  1079. CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
  1080. Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
  1081. for (unsigned i = 1, e = VL.size(); i < e; ++i) {
  1082. CmpInst *Cmp = cast<CmpInst>(VL[i]);
  1083. if (Cmp->getPredicate() != P0 ||
  1084. Cmp->getOperand(0)->getType() != ComparedTy) {
  1085. BS.cancelScheduling(VL);
  1086. newTreeEntry(VL, false);
  1087. DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
  1088. return;
  1089. }
  1090. }
  1091. newTreeEntry(VL, true);
  1092. DEBUG(dbgs() << "SLP: added a vector of compares.\n");
  1093. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  1094. ValueList Operands;
  1095. // Prepare the operand vector.
  1096. for (Value *j : VL)
  1097. Operands.push_back(cast<Instruction>(j)->getOperand(i));
  1098. buildTree_rec(Operands, Depth+1);
  1099. }
  1100. return;
  1101. }
  1102. case Instruction::Select:
  1103. case Instruction::Add:
  1104. case Instruction::FAdd:
  1105. case Instruction::Sub:
  1106. case Instruction::FSub:
  1107. case Instruction::Mul:
  1108. case Instruction::FMul:
  1109. case Instruction::UDiv:
  1110. case Instruction::SDiv:
  1111. case Instruction::FDiv:
  1112. case Instruction::URem:
  1113. case Instruction::SRem:
  1114. case Instruction::FRem:
  1115. case Instruction::Shl:
  1116. case Instruction::LShr:
  1117. case Instruction::AShr:
  1118. case Instruction::And:
  1119. case Instruction::Or:
  1120. case Instruction::Xor: {
  1121. newTreeEntry(VL, true);
  1122. DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
  1123. // Sort operands of the instructions so that each side is more likely to
  1124. // have the same opcode.
  1125. if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
  1126. ValueList Left, Right;
  1127. reorderInputsAccordingToOpcode(VL, Left, Right);
  1128. buildTree_rec(Left, Depth + 1);
  1129. buildTree_rec(Right, Depth + 1);
  1130. return;
  1131. }
  1132. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  1133. ValueList Operands;
  1134. // Prepare the operand vector.
  1135. for (Value *j : VL)
  1136. Operands.push_back(cast<Instruction>(j)->getOperand(i));
  1137. buildTree_rec(Operands, Depth+1);
  1138. }
  1139. return;
  1140. }
  1141. case Instruction::GetElementPtr: {
  1142. // We don't combine GEPs with complicated (nested) indexing.
  1143. for (unsigned j = 0; j < VL.size(); ++j) {
  1144. if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
  1145. DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
  1146. BS.cancelScheduling(VL);
  1147. newTreeEntry(VL, false);
  1148. return;
  1149. }
  1150. }
  1151. // We can't combine several GEPs into one vector if they operate on
  1152. // different types.
  1153. Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
  1154. for (unsigned j = 0; j < VL.size(); ++j) {
  1155. Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
  1156. if (Ty0 != CurTy) {
  1157. DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
  1158. BS.cancelScheduling(VL);
  1159. newTreeEntry(VL, false);
  1160. return;
  1161. }
  1162. }
  1163. // We don't combine GEPs with non-constant indexes.
  1164. for (unsigned j = 0; j < VL.size(); ++j) {
  1165. auto Op = cast<Instruction>(VL[j])->getOperand(1);
  1166. if (!isa<ConstantInt>(Op)) {
  1167. DEBUG(
  1168. dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
  1169. BS.cancelScheduling(VL);
  1170. newTreeEntry(VL, false);
  1171. return;
  1172. }
  1173. }
  1174. newTreeEntry(VL, true);
  1175. DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
  1176. for (unsigned i = 0, e = 2; i < e; ++i) {
  1177. ValueList Operands;
  1178. // Prepare the operand vector.
  1179. for (Value *j : VL)
  1180. Operands.push_back(cast<Instruction>(j)->getOperand(i));
  1181. buildTree_rec(Operands, Depth + 1);
  1182. }
  1183. return;
  1184. }
  1185. case Instruction::Store: {
  1186. // Check if the stores are consecutive or of we need to swizzle them.
  1187. for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
  1188. if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
  1189. BS.cancelScheduling(VL);
  1190. newTreeEntry(VL, false);
  1191. DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
  1192. return;
  1193. }
  1194. newTreeEntry(VL, true);
  1195. DEBUG(dbgs() << "SLP: added a vector of stores.\n");
  1196. ValueList Operands;
  1197. for (Value *j : VL)
  1198. Operands.push_back(cast<Instruction>(j)->getOperand(0));
  1199. buildTree_rec(Operands, Depth + 1);
  1200. return;
  1201. }
  1202. case Instruction::Call: {
  1203. // Check if the calls are all to the same vectorizable intrinsic.
  1204. CallInst *CI = cast<CallInst>(VL[0]);
  1205. // Check if this is an Intrinsic call or something that can be
  1206. // represented by an intrinsic call
  1207. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  1208. if (!isTriviallyVectorizable(ID)) {
  1209. BS.cancelScheduling(VL);
  1210. newTreeEntry(VL, false);
  1211. DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
  1212. return;
  1213. }
  1214. Function *Int = CI->getCalledFunction();
  1215. Value *A1I = nullptr;
  1216. if (hasVectorInstrinsicScalarOpd(ID, 1))
  1217. A1I = CI->getArgOperand(1);
  1218. for (unsigned i = 1, e = VL.size(); i != e; ++i) {
  1219. CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
  1220. if (!CI2 || CI2->getCalledFunction() != Int ||
  1221. getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
  1222. !CI->hasIdenticalOperandBundleSchema(*CI2)) {
  1223. BS.cancelScheduling(VL);
  1224. newTreeEntry(VL, false);
  1225. DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
  1226. << "\n");
  1227. return;
  1228. }
  1229. // ctlz,cttz and powi are special intrinsics whose second argument
  1230. // should be same in order for them to be vectorized.
  1231. if (hasVectorInstrinsicScalarOpd(ID, 1)) {
  1232. Value *A1J = CI2->getArgOperand(1);
  1233. if (A1I != A1J) {
  1234. BS.cancelScheduling(VL);
  1235. newTreeEntry(VL, false);
  1236. DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
  1237. << " argument "<< A1I<<"!=" << A1J
  1238. << "\n");
  1239. return;
  1240. }
  1241. }
  1242. // Verify that the bundle operands are identical between the two calls.
  1243. if (CI->hasOperandBundles() &&
  1244. !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
  1245. CI->op_begin() + CI->getBundleOperandsEndIndex(),
  1246. CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
  1247. BS.cancelScheduling(VL);
  1248. newTreeEntry(VL, false);
  1249. DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!="
  1250. << *VL[i] << '\n');
  1251. return;
  1252. }
  1253. }
  1254. newTreeEntry(VL, true);
  1255. for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
  1256. ValueList Operands;
  1257. // Prepare the operand vector.
  1258. for (Value *j : VL) {
  1259. CallInst *CI2 = dyn_cast<CallInst>(j);
  1260. Operands.push_back(CI2->getArgOperand(i));
  1261. }
  1262. buildTree_rec(Operands, Depth + 1);
  1263. }
  1264. return;
  1265. }
  1266. case Instruction::ShuffleVector: {
  1267. // If this is not an alternate sequence of opcode like add-sub
  1268. // then do not vectorize this instruction.
  1269. if (!isAltShuffle) {
  1270. BS.cancelScheduling(VL);
  1271. newTreeEntry(VL, false);
  1272. DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
  1273. return;
  1274. }
  1275. newTreeEntry(VL, true);
  1276. DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
  1277. // Reorder operands if reordering would enable vectorization.
  1278. if (isa<BinaryOperator>(VL0)) {
  1279. ValueList Left, Right;
  1280. reorderAltShuffleOperands(VL, Left, Right);
  1281. buildTree_rec(Left, Depth + 1);
  1282. buildTree_rec(Right, Depth + 1);
  1283. return;
  1284. }
  1285. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  1286. ValueList Operands;
  1287. // Prepare the operand vector.
  1288. for (Value *j : VL)
  1289. Operands.push_back(cast<Instruction>(j)->getOperand(i));
  1290. buildTree_rec(Operands, Depth + 1);
  1291. }
  1292. return;
  1293. }
  1294. default:
  1295. BS.cancelScheduling(VL);
  1296. newTreeEntry(VL, false);
  1297. DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
  1298. return;
  1299. }
  1300. }
  1301. unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
  1302. unsigned N;
  1303. Type *EltTy;
  1304. auto *ST = dyn_cast<StructType>(T);
  1305. if (ST) {
  1306. N = ST->getNumElements();
  1307. EltTy = *ST->element_begin();
  1308. } else {
  1309. N = cast<ArrayType>(T)->getNumElements();
  1310. EltTy = cast<ArrayType>(T)->getElementType();
  1311. }
  1312. if (!isValidElementType(EltTy))
  1313. return 0;
  1314. uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
  1315. if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
  1316. return 0;
  1317. if (ST) {
  1318. // Check that struct is homogeneous.
  1319. for (const auto *Ty : ST->elements())
  1320. if (Ty != EltTy)
  1321. return 0;
  1322. }
  1323. return N;
  1324. }
  1325. bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, unsigned Opcode) const {
  1326. assert(Opcode == Instruction::ExtractElement ||
  1327. Opcode == Instruction::ExtractValue);
  1328. assert(Opcode == getSameOpcode(VL) && "Invalid opcode");
  1329. // Check if all of the extracts come from the same vector and from the
  1330. // correct offset.
  1331. Value *VL0 = VL[0];
  1332. Instruction *E0 = cast<Instruction>(VL0);
  1333. Value *Vec = E0->getOperand(0);
  1334. // We have to extract from a vector/aggregate with the same number of elements.
  1335. unsigned NElts;
  1336. if (Opcode == Instruction::ExtractValue) {
  1337. const DataLayout &DL = E0->getModule()->getDataLayout();
  1338. NElts = canMapToVector(Vec->getType(), DL);
  1339. if (!NElts)
  1340. return false;
  1341. // Check if load can be rewritten as load of vector.
  1342. LoadInst *LI = dyn_cast<LoadInst>(Vec);
  1343. if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
  1344. return false;
  1345. } else {
  1346. NElts = Vec->getType()->getVectorNumElements();
  1347. }
  1348. if (NElts != VL.size())
  1349. return false;
  1350. // Check that all of the indices extract from the correct offset.
  1351. if (!matchExtractIndex(E0, 0, Opcode))
  1352. return false;
  1353. for (unsigned i = 1, e = VL.size(); i < e; ++i) {
  1354. Instruction *E = cast<Instruction>(VL[i]);
  1355. if (!matchExtractIndex(E, i, Opcode))
  1356. return false;
  1357. if (E->getOperand(0) != Vec)
  1358. return false;
  1359. }
  1360. return true;
  1361. }
  1362. int BoUpSLP::getEntryCost(TreeEntry *E) {
  1363. ArrayRef<Value*> VL = E->Scalars;
  1364. Type *ScalarTy = VL[0]->getType();
  1365. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  1366. ScalarTy = SI->getValueOperand()->getType();
  1367. VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
  1368. // If we have computed a smaller type for the expression, update VecTy so
  1369. // that the costs will be accurate.
  1370. if (MinBWs.count(VL[0]))
  1371. VecTy = VectorType::get(
  1372. IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
  1373. if (E->NeedToGather) {
  1374. if (allConstant(VL))
  1375. return 0;
  1376. if (isSplat(VL)) {
  1377. return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
  1378. }
  1379. return getGatherCost(E->Scalars);
  1380. }
  1381. unsigned Opcode = getSameOpcode(VL);
  1382. assert(Opcode && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
  1383. Instruction *VL0 = cast<Instruction>(VL[0]);
  1384. switch (Opcode) {
  1385. case Instruction::PHI: {
  1386. return 0;
  1387. }
  1388. case Instruction::ExtractValue:
  1389. case Instruction::ExtractElement: {
  1390. if (canReuseExtract(VL, Opcode)) {
  1391. int DeadCost = 0;
  1392. for (unsigned i = 0, e = VL.size(); i < e; ++i) {
  1393. Instruction *E = cast<Instruction>(VL[i]);
  1394. if (E->hasOneUse())
  1395. // Take credit for instruction that will become dead.
  1396. DeadCost +=
  1397. TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
  1398. }
  1399. return -DeadCost;
  1400. }
  1401. return getGatherCost(VecTy);
  1402. }
  1403. case Instruction::ZExt:
  1404. case Instruction::SExt:
  1405. case Instruction::FPToUI:
  1406. case Instruction::FPToSI:
  1407. case Instruction::FPExt:
  1408. case Instruction::PtrToInt:
  1409. case Instruction::IntToPtr:
  1410. case Instruction::SIToFP:
  1411. case Instruction::UIToFP:
  1412. case Instruction::Trunc:
  1413. case Instruction::FPTrunc:
  1414. case Instruction::BitCast: {
  1415. Type *SrcTy = VL0->getOperand(0)->getType();
  1416. // Calculate the cost of this instruction.
  1417. int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
  1418. VL0->getType(), SrcTy);
  1419. VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
  1420. int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
  1421. return VecCost - ScalarCost;
  1422. }
  1423. case Instruction::FCmp:
  1424. case Instruction::ICmp:
  1425. case Instruction::Select: {
  1426. // Calculate the cost of this instruction.
  1427. VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
  1428. int ScalarCost = VecTy->getNumElements() *
  1429. TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
  1430. int VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
  1431. return VecCost - ScalarCost;
  1432. }
  1433. case Instruction::Add:
  1434. case Instruction::FAdd:
  1435. case Instruction::Sub:
  1436. case Instruction::FSub:
  1437. case Instruction::Mul:
  1438. case Instruction::FMul:
  1439. case Instruction::UDiv:
  1440. case Instruction::SDiv:
  1441. case Instruction::FDiv:
  1442. case Instruction::URem:
  1443. case Instruction::SRem:
  1444. case Instruction::FRem:
  1445. case Instruction::Shl:
  1446. case Instruction::LShr:
  1447. case Instruction::AShr:
  1448. case Instruction::And:
  1449. case Instruction::Or:
  1450. case Instruction::Xor: {
  1451. // Certain instructions can be cheaper to vectorize if they have a
  1452. // constant second vector operand.
  1453. TargetTransformInfo::OperandValueKind Op1VK =
  1454. TargetTransformInfo::OK_AnyValue;
  1455. TargetTransformInfo::OperandValueKind Op2VK =
  1456. TargetTransformInfo::OK_UniformConstantValue;
  1457. TargetTransformInfo::OperandValueProperties Op1VP =
  1458. TargetTransformInfo::OP_None;
  1459. TargetTransformInfo::OperandValueProperties Op2VP =
  1460. TargetTransformInfo::OP_None;
  1461. // If all operands are exactly the same ConstantInt then set the
  1462. // operand kind to OK_UniformConstantValue.
  1463. // If instead not all operands are constants, then set the operand kind
  1464. // to OK_AnyValue. If all operands are constants but not the same,
  1465. // then set the operand kind to OK_NonUniformConstantValue.
  1466. ConstantInt *CInt = nullptr;
  1467. for (unsigned i = 0; i < VL.size(); ++i) {
  1468. const Instruction *I = cast<Instruction>(VL[i]);
  1469. if (!isa<ConstantInt>(I->getOperand(1))) {
  1470. Op2VK = TargetTransformInfo::OK_AnyValue;
  1471. break;
  1472. }
  1473. if (i == 0) {
  1474. CInt = cast<ConstantInt>(I->getOperand(1));
  1475. continue;
  1476. }
  1477. if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
  1478. CInt != cast<ConstantInt>(I->getOperand(1)))
  1479. Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
  1480. }
  1481. // FIXME: Currently cost of model modification for division by power of
  1482. // 2 is handled for X86 and AArch64. Add support for other targets.
  1483. if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
  1484. CInt->getValue().isPowerOf2())
  1485. Op2VP = TargetTransformInfo::OP_PowerOf2;
  1486. int ScalarCost = VecTy->getNumElements() *
  1487. TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK,
  1488. Op2VK, Op1VP, Op2VP);
  1489. int VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
  1490. Op1VP, Op2VP);
  1491. return VecCost - ScalarCost;
  1492. }
  1493. case Instruction::GetElementPtr: {
  1494. TargetTransformInfo::OperandValueKind Op1VK =
  1495. TargetTransformInfo::OK_AnyValue;
  1496. TargetTransformInfo::OperandValueKind Op2VK =
  1497. TargetTransformInfo::OK_UniformConstantValue;
  1498. int ScalarCost =
  1499. VecTy->getNumElements() *
  1500. TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
  1501. int VecCost =
  1502. TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
  1503. return VecCost - ScalarCost;
  1504. }
  1505. case Instruction::Load: {
  1506. // Cost of wide load - cost of scalar loads.
  1507. unsigned alignment = dyn_cast<LoadInst>(VL0)->getAlignment();
  1508. int ScalarLdCost = VecTy->getNumElements() *
  1509. TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0);
  1510. int VecLdCost = TTI->getMemoryOpCost(Instruction::Load,
  1511. VecTy, alignment, 0);
  1512. return VecLdCost - ScalarLdCost;
  1513. }
  1514. case Instruction::Store: {
  1515. // We know that we can merge the stores. Calculate the cost.
  1516. unsigned alignment = dyn_cast<StoreInst>(VL0)->getAlignment();
  1517. int ScalarStCost = VecTy->getNumElements() *
  1518. TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0);
  1519. int VecStCost = TTI->getMemoryOpCost(Instruction::Store,
  1520. VecTy, alignment, 0);
  1521. return VecStCost - ScalarStCost;
  1522. }
  1523. case Instruction::Call: {
  1524. CallInst *CI = cast<CallInst>(VL0);
  1525. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  1526. // Calculate the cost of the scalar and vector calls.
  1527. SmallVector<Type*, 4> ScalarTys, VecTys;
  1528. for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
  1529. ScalarTys.push_back(CI->getArgOperand(op)->getType());
  1530. VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
  1531. VecTy->getNumElements()));
  1532. }
  1533. FastMathFlags FMF;
  1534. if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
  1535. FMF = FPMO->getFastMathFlags();
  1536. int ScalarCallCost = VecTy->getNumElements() *
  1537. TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
  1538. int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys, FMF);
  1539. DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
  1540. << " (" << VecCallCost << "-" << ScalarCallCost << ")"
  1541. << " for " << *CI << "\n");
  1542. return VecCallCost - ScalarCallCost;
  1543. }
  1544. case Instruction::ShuffleVector: {
  1545. TargetTransformInfo::OperandValueKind Op1VK =
  1546. TargetTransformInfo::OK_AnyValue;
  1547. TargetTransformInfo::OperandValueKind Op2VK =
  1548. TargetTransformInfo::OK_AnyValue;
  1549. int ScalarCost = 0;
  1550. int VecCost = 0;
  1551. for (Value *i : VL) {
  1552. Instruction *I = cast<Instruction>(i);
  1553. if (!I)
  1554. break;
  1555. ScalarCost +=
  1556. TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
  1557. }
  1558. // VecCost is equal to sum of the cost of creating 2 vectors
  1559. // and the cost of creating shuffle.
  1560. Instruction *I0 = cast<Instruction>(VL[0]);
  1561. VecCost =
  1562. TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
  1563. Instruction *I1 = cast<Instruction>(VL[1]);
  1564. VecCost +=
  1565. TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
  1566. VecCost +=
  1567. TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
  1568. return VecCost - ScalarCost;
  1569. }
  1570. default:
  1571. llvm_unreachable("Unknown instruction");
  1572. }
  1573. }
  1574. bool BoUpSLP::isFullyVectorizableTinyTree() {
  1575. DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
  1576. VectorizableTree.size() << " is fully vectorizable .\n");
  1577. // We only handle trees of heights 1 and 2.
  1578. if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
  1579. return true;
  1580. if (VectorizableTree.size() != 2)
  1581. return false;
  1582. // Handle splat and all-constants stores.
  1583. if (!VectorizableTree[0].NeedToGather &&
  1584. (allConstant(VectorizableTree[1].Scalars) ||
  1585. isSplat(VectorizableTree[1].Scalars)))
  1586. return true;
  1587. // Gathering cost would be too much for tiny trees.
  1588. if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
  1589. return false;
  1590. return true;
  1591. }
  1592. bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
  1593. // We can vectorize the tree if its size is greater than or equal to the
  1594. // minimum size specified by the MinTreeSize command line option.
  1595. if (VectorizableTree.size() >= MinTreeSize)
  1596. return false;
  1597. // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
  1598. // can vectorize it if we can prove it fully vectorizable.
  1599. if (isFullyVectorizableTinyTree())
  1600. return false;
  1601. assert(VectorizableTree.empty()
  1602. ? ExternalUses.empty()
  1603. : true && "We shouldn't have any external users");
  1604. // Otherwise, we can't vectorize the tree. It is both tiny and not fully
  1605. // vectorizable.
  1606. return true;
  1607. }
  1608. int BoUpSLP::getSpillCost() {
  1609. // Walk from the bottom of the tree to the top, tracking which values are
  1610. // live. When we see a call instruction that is not part of our tree,
  1611. // query TTI to see if there is a cost to keeping values live over it
  1612. // (for example, if spills and fills are required).
  1613. unsigned BundleWidth = VectorizableTree.front().Scalars.size();
  1614. int Cost = 0;
  1615. SmallPtrSet<Instruction*, 4> LiveValues;
  1616. Instruction *PrevInst = nullptr;
  1617. for (const auto &N : VectorizableTree) {
  1618. Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
  1619. if (!Inst)
  1620. continue;
  1621. if (!PrevInst) {
  1622. PrevInst = Inst;
  1623. continue;
  1624. }
  1625. // Update LiveValues.
  1626. LiveValues.erase(PrevInst);
  1627. for (auto &J : PrevInst->operands()) {
  1628. if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
  1629. LiveValues.insert(cast<Instruction>(&*J));
  1630. }
  1631. DEBUG(
  1632. dbgs() << "SLP: #LV: " << LiveValues.size();
  1633. for (auto *X : LiveValues)
  1634. dbgs() << " " << X->getName();
  1635. dbgs() << ", Looking at ";
  1636. Inst->dump();
  1637. );
  1638. // Now find the sequence of instructions between PrevInst and Inst.
  1639. BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
  1640. PrevInstIt =
  1641. PrevInst->getIterator().getReverse();
  1642. while (InstIt != PrevInstIt) {
  1643. if (PrevInstIt == PrevInst->getParent()->rend()) {
  1644. PrevInstIt = Inst->getParent()->rbegin();
  1645. continue;
  1646. }
  1647. if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
  1648. SmallVector<Type*, 4> V;
  1649. for (auto *II : LiveValues)
  1650. V.push_back(VectorType::get(II->getType(), BundleWidth));
  1651. Cost += TTI->getCostOfKeepingLiveOverCall(V);
  1652. }
  1653. ++PrevInstIt;
  1654. }
  1655. PrevInst = Inst;
  1656. }
  1657. return Cost;
  1658. }
  1659. int BoUpSLP::getTreeCost() {
  1660. int Cost = 0;
  1661. DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
  1662. VectorizableTree.size() << ".\n");
  1663. unsigned BundleWidth = VectorizableTree[0].Scalars.size();
  1664. for (TreeEntry &TE : VectorizableTree) {
  1665. int C = getEntryCost(&TE);
  1666. DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
  1667. << *TE.Scalars[0] << ".\n");
  1668. Cost += C;
  1669. }
  1670. SmallSet<Value *, 16> ExtractCostCalculated;
  1671. int ExtractCost = 0;
  1672. for (ExternalUser &EU : ExternalUses) {
  1673. // We only add extract cost once for the same scalar.
  1674. if (!ExtractCostCalculated.insert(EU.Scalar).second)
  1675. continue;
  1676. // Uses by ephemeral values are free (because the ephemeral value will be
  1677. // removed prior to code generation, and so the extraction will be
  1678. // removed as well).
  1679. if (EphValues.count(EU.User))
  1680. continue;
  1681. // If we plan to rewrite the tree in a smaller type, we will need to sign
  1682. // extend the extracted value back to the original type. Here, we account
  1683. // for the extract and the added cost of the sign extend if needed.
  1684. auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
  1685. auto *ScalarRoot = VectorizableTree[0].Scalars[0];
  1686. if (MinBWs.count(ScalarRoot)) {
  1687. auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
  1688. auto Extend =
  1689. MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
  1690. VecTy = VectorType::get(MinTy, BundleWidth);
  1691. ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
  1692. VecTy, EU.Lane);
  1693. } else {
  1694. ExtractCost +=
  1695. TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
  1696. }
  1697. }
  1698. int SpillCost = getSpillCost();
  1699. Cost += SpillCost + ExtractCost;
  1700. DEBUG(dbgs() << "SLP: Spill Cost = " << SpillCost << ".\n"
  1701. << "SLP: Extract Cost = " << ExtractCost << ".\n"
  1702. << "SLP: Total Cost = " << Cost << ".\n");
  1703. return Cost;
  1704. }
  1705. int BoUpSLP::getGatherCost(Type *Ty) {
  1706. int Cost = 0;
  1707. for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
  1708. Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
  1709. return Cost;
  1710. }
  1711. int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
  1712. // Find the type of the operands in VL.
  1713. Type *ScalarTy = VL[0]->getType();
  1714. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  1715. ScalarTy = SI->getValueOperand()->getType();
  1716. VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
  1717. // Find the cost of inserting/extracting values from the vector.
  1718. return getGatherCost(VecTy);
  1719. }
  1720. // Reorder commutative operations in alternate shuffle if the resulting vectors
  1721. // are consecutive loads. This would allow us to vectorize the tree.
  1722. // If we have something like-
  1723. // load a[0] - load b[0]
  1724. // load b[1] + load a[1]
  1725. // load a[2] - load b[2]
  1726. // load a[3] + load b[3]
  1727. // Reordering the second load b[1] load a[1] would allow us to vectorize this
  1728. // code.
  1729. void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
  1730. SmallVectorImpl<Value *> &Left,
  1731. SmallVectorImpl<Value *> &Right) {
  1732. // Push left and right operands of binary operation into Left and Right
  1733. for (Value *i : VL) {
  1734. Left.push_back(cast<Instruction>(i)->getOperand(0));
  1735. Right.push_back(cast<Instruction>(i)->getOperand(1));
  1736. }
  1737. // Reorder if we have a commutative operation and consecutive access
  1738. // are on either side of the alternate instructions.
  1739. for (unsigned j = 0; j < VL.size() - 1; ++j) {
  1740. if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
  1741. if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
  1742. Instruction *VL1 = cast<Instruction>(VL[j]);
  1743. Instruction *VL2 = cast<Instruction>(VL[j + 1]);
  1744. if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
  1745. std::swap(Left[j], Right[j]);
  1746. continue;
  1747. } else if (VL2->isCommutative() &&
  1748. isConsecutiveAccess(L, L1, *DL, *SE)) {
  1749. std::swap(Left[j + 1], Right[j + 1]);
  1750. continue;
  1751. }
  1752. // else unchanged
  1753. }
  1754. }
  1755. if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
  1756. if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
  1757. Instruction *VL1 = cast<Instruction>(VL[j]);
  1758. Instruction *VL2 = cast<Instruction>(VL[j + 1]);
  1759. if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
  1760. std::swap(Left[j], Right[j]);
  1761. continue;
  1762. } else if (VL2->isCommutative() &&
  1763. isConsecutiveAccess(L, L1, *DL, *SE)) {
  1764. std::swap(Left[j + 1], Right[j + 1]);
  1765. continue;
  1766. }
  1767. // else unchanged
  1768. }
  1769. }
  1770. }
  1771. }
  1772. // Return true if I should be commuted before adding it's left and right
  1773. // operands to the arrays Left and Right.
  1774. //
  1775. // The vectorizer is trying to either have all elements one side being
  1776. // instruction with the same opcode to enable further vectorization, or having
  1777. // a splat to lower the vectorizing cost.
  1778. static bool shouldReorderOperands(int i, Instruction &I,
  1779. SmallVectorImpl<Value *> &Left,
  1780. SmallVectorImpl<Value *> &Right,
  1781. bool AllSameOpcodeLeft,
  1782. bool AllSameOpcodeRight, bool SplatLeft,
  1783. bool SplatRight) {
  1784. Value *VLeft = I.getOperand(0);
  1785. Value *VRight = I.getOperand(1);
  1786. // If we have "SplatRight", try to see if commuting is needed to preserve it.
  1787. if (SplatRight) {
  1788. if (VRight == Right[i - 1])
  1789. // Preserve SplatRight
  1790. return false;
  1791. if (VLeft == Right[i - 1]) {
  1792. // Commuting would preserve SplatRight, but we don't want to break
  1793. // SplatLeft either, i.e. preserve the original order if possible.
  1794. // (FIXME: why do we care?)
  1795. if (SplatLeft && VLeft == Left[i - 1])
  1796. return false;
  1797. return true;
  1798. }
  1799. }
  1800. // Symmetrically handle Right side.
  1801. if (SplatLeft) {
  1802. if (VLeft == Left[i - 1])
  1803. // Preserve SplatLeft
  1804. return false;
  1805. if (VRight == Left[i - 1])
  1806. return true;
  1807. }
  1808. Instruction *ILeft = dyn_cast<Instruction>(VLeft);
  1809. Instruction *IRight = dyn_cast<Instruction>(VRight);
  1810. // If we have "AllSameOpcodeRight", try to see if the left operands preserves
  1811. // it and not the right, in this case we want to commute.
  1812. if (AllSameOpcodeRight) {
  1813. unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
  1814. if (IRight && RightPrevOpcode == IRight->getOpcode())
  1815. // Do not commute, a match on the right preserves AllSameOpcodeRight
  1816. return false;
  1817. if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
  1818. // We have a match and may want to commute, but first check if there is
  1819. // not also a match on the existing operands on the Left to preserve
  1820. // AllSameOpcodeLeft, i.e. preserve the original order if possible.
  1821. // (FIXME: why do we care?)
  1822. if (AllSameOpcodeLeft && ILeft &&
  1823. cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
  1824. return false;
  1825. return true;
  1826. }
  1827. }
  1828. // Symmetrically handle Left side.
  1829. if (AllSameOpcodeLeft) {
  1830. unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
  1831. if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
  1832. return false;
  1833. if (IRight && LeftPrevOpcode == IRight->getOpcode())
  1834. return true;
  1835. }
  1836. return false;
  1837. }
  1838. void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
  1839. SmallVectorImpl<Value *> &Left,
  1840. SmallVectorImpl<Value *> &Right) {
  1841. if (VL.size()) {
  1842. // Peel the first iteration out of the loop since there's nothing
  1843. // interesting to do anyway and it simplifies the checks in the loop.
  1844. auto VLeft = cast<Instruction>(VL[0])->getOperand(0);
  1845. auto VRight = cast<Instruction>(VL[0])->getOperand(1);
  1846. if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
  1847. // Favor having instruction to the right. FIXME: why?
  1848. std::swap(VLeft, VRight);
  1849. Left.push_back(VLeft);
  1850. Right.push_back(VRight);
  1851. }
  1852. // Keep track if we have instructions with all the same opcode on one side.
  1853. bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
  1854. bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
  1855. // Keep track if we have one side with all the same value (broadcast).
  1856. bool SplatLeft = true;
  1857. bool SplatRight = true;
  1858. for (unsigned i = 1, e = VL.size(); i != e; ++i) {
  1859. Instruction *I = cast<Instruction>(VL[i]);
  1860. assert(I->isCommutative() && "Can only process commutative instruction");
  1861. // Commute to favor either a splat or maximizing having the same opcodes on
  1862. // one side.
  1863. if (shouldReorderOperands(i, *I, Left, Right, AllSameOpcodeLeft,
  1864. AllSameOpcodeRight, SplatLeft, SplatRight)) {
  1865. Left.push_back(I->getOperand(1));
  1866. Right.push_back(I->getOperand(0));
  1867. } else {
  1868. Left.push_back(I->getOperand(0));
  1869. Right.push_back(I->getOperand(1));
  1870. }
  1871. // Update Splat* and AllSameOpcode* after the insertion.
  1872. SplatRight = SplatRight && (Right[i - 1] == Right[i]);
  1873. SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
  1874. AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
  1875. (cast<Instruction>(Left[i - 1])->getOpcode() ==
  1876. cast<Instruction>(Left[i])->getOpcode());
  1877. AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
  1878. (cast<Instruction>(Right[i - 1])->getOpcode() ==
  1879. cast<Instruction>(Right[i])->getOpcode());
  1880. }
  1881. // If one operand end up being broadcast, return this operand order.
  1882. if (SplatRight || SplatLeft)
  1883. return;
  1884. // Finally check if we can get longer vectorizable chain by reordering
  1885. // without breaking the good operand order detected above.
  1886. // E.g. If we have something like-
  1887. // load a[0] load b[0]
  1888. // load b[1] load a[1]
  1889. // load a[2] load b[2]
  1890. // load a[3] load b[3]
  1891. // Reordering the second load b[1] load a[1] would allow us to vectorize
  1892. // this code and we still retain AllSameOpcode property.
  1893. // FIXME: This load reordering might break AllSameOpcode in some rare cases
  1894. // such as-
  1895. // add a[0],c[0] load b[0]
  1896. // add a[1],c[2] load b[1]
  1897. // b[2] load b[2]
  1898. // add a[3],c[3] load b[3]
  1899. for (unsigned j = 0; j < VL.size() - 1; ++j) {
  1900. if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
  1901. if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
  1902. if (isConsecutiveAccess(L, L1, *DL, *SE)) {
  1903. std::swap(Left[j + 1], Right[j + 1]);
  1904. continue;
  1905. }
  1906. }
  1907. }
  1908. if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
  1909. if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
  1910. if (isConsecutiveAccess(L, L1, *DL, *SE)) {
  1911. std::swap(Left[j + 1], Right[j + 1]);
  1912. continue;
  1913. }
  1914. }
  1915. }
  1916. // else unchanged
  1917. }
  1918. }
  1919. void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
  1920. // Get the basic block this bundle is in. All instructions in the bundle
  1921. // should be in this block.
  1922. auto *Front = cast<Instruction>(VL.front());
  1923. auto *BB = Front->getParent();
  1924. assert(all_of(make_range(VL.begin(), VL.end()), [&](Value *V) -> bool {
  1925. return cast<Instruction>(V)->getParent() == BB;
  1926. }));
  1927. // The last instruction in the bundle in program order.
  1928. Instruction *LastInst = nullptr;
  1929. // Find the last instruction. The common case should be that BB has been
  1930. // scheduled, and the last instruction is VL.back(). So we start with
  1931. // VL.back() and iterate over schedule data until we reach the end of the
  1932. // bundle. The end of the bundle is marked by null ScheduleData.
  1933. if (BlocksSchedules.count(BB)) {
  1934. auto *Bundle = BlocksSchedules[BB]->getScheduleData(VL.back());
  1935. if (Bundle && Bundle->isPartOfBundle())
  1936. for (; Bundle; Bundle = Bundle->NextInBundle)
  1937. LastInst = Bundle->Inst;
  1938. }
  1939. // LastInst can still be null at this point if there's either not an entry
  1940. // for BB in BlocksSchedules or there's no ScheduleData available for
  1941. // VL.back(). This can be the case if buildTree_rec aborts for various
  1942. // reasons (e.g., the maximum recursion depth is reached, the maximum region
  1943. // size is reached, etc.). ScheduleData is initialized in the scheduling
  1944. // "dry-run".
  1945. //
  1946. // If this happens, we can still find the last instruction by brute force. We
  1947. // iterate forwards from Front (inclusive) until we either see all
  1948. // instructions in the bundle or reach the end of the block. If Front is the
  1949. // last instruction in program order, LastInst will be set to Front, and we
  1950. // will visit all the remaining instructions in the block.
  1951. //
  1952. // One of the reasons we exit early from buildTree_rec is to place an upper
  1953. // bound on compile-time. Thus, taking an additional compile-time hit here is
  1954. // not ideal. However, this should be exceedingly rare since it requires that
  1955. // we both exit early from buildTree_rec and that the bundle be out-of-order
  1956. // (causing us to iterate all the way to the end of the block).
  1957. if (!LastInst) {
  1958. SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
  1959. for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
  1960. if (Bundle.erase(&I))
  1961. LastInst = &I;
  1962. if (Bundle.empty())
  1963. break;
  1964. }
  1965. }
  1966. // Set the insertion point after the last instruction in the bundle. Set the
  1967. // debug location to Front.
  1968. Builder.SetInsertPoint(BB, ++LastInst->getIterator());
  1969. Builder.SetCurrentDebugLocation(Front->getDebugLoc());
  1970. }
  1971. Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
  1972. Value *Vec = UndefValue::get(Ty);
  1973. // Generate the 'InsertElement' instruction.
  1974. for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
  1975. Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
  1976. if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
  1977. GatherSeq.insert(Insrt);
  1978. CSEBlocks.insert(Insrt->getParent());
  1979. // Add to our 'need-to-extract' list.
  1980. if (ScalarToTreeEntry.count(VL[i])) {
  1981. int Idx = ScalarToTreeEntry[VL[i]];
  1982. TreeEntry *E = &VectorizableTree[Idx];
  1983. // Find which lane we need to extract.
  1984. int FoundLane = -1;
  1985. for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
  1986. // Is this the lane of the scalar that we are looking for ?
  1987. if (E->Scalars[Lane] == VL[i]) {
  1988. FoundLane = Lane;
  1989. break;
  1990. }
  1991. }
  1992. assert(FoundLane >= 0 && "Could not find the correct lane");
  1993. ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
  1994. }
  1995. }
  1996. }
  1997. return Vec;
  1998. }
  1999. Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
  2000. SmallDenseMap<Value*, int>::const_iterator Entry
  2001. = ScalarToTreeEntry.find(VL[0]);
  2002. if (Entry != ScalarToTreeEntry.end()) {
  2003. int Idx = Entry->second;
  2004. const TreeEntry *En = &VectorizableTree[Idx];
  2005. if (En->isSame(VL) && En->VectorizedValue)
  2006. return En->VectorizedValue;
  2007. }
  2008. return nullptr;
  2009. }
  2010. Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
  2011. if (ScalarToTreeEntry.count(VL[0])) {
  2012. int Idx = ScalarToTreeEntry[VL[0]];
  2013. TreeEntry *E = &VectorizableTree[Idx];
  2014. if (E->isSame(VL))
  2015. return vectorizeTree(E);
  2016. }
  2017. Type *ScalarTy = VL[0]->getType();
  2018. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  2019. ScalarTy = SI->getValueOperand()->getType();
  2020. VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
  2021. return Gather(VL, VecTy);
  2022. }
  2023. Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
  2024. IRBuilder<>::InsertPointGuard Guard(Builder);
  2025. if (E->VectorizedValue) {
  2026. DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
  2027. return E->VectorizedValue;
  2028. }
  2029. Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
  2030. Type *ScalarTy = VL0->getType();
  2031. if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
  2032. ScalarTy = SI->getValueOperand()->getType();
  2033. VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
  2034. if (E->NeedToGather) {
  2035. setInsertPointAfterBundle(E->Scalars);
  2036. auto *V = Gather(E->Scalars, VecTy);
  2037. E->VectorizedValue = V;
  2038. return V;
  2039. }
  2040. unsigned Opcode = getSameOpcode(E->Scalars);
  2041. switch (Opcode) {
  2042. case Instruction::PHI: {
  2043. PHINode *PH = dyn_cast<PHINode>(VL0);
  2044. Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
  2045. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  2046. PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
  2047. E->VectorizedValue = NewPhi;
  2048. // PHINodes may have multiple entries from the same block. We want to
  2049. // visit every block once.
  2050. SmallSet<BasicBlock*, 4> VisitedBBs;
  2051. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  2052. ValueList Operands;
  2053. BasicBlock *IBB = PH->getIncomingBlock(i);
  2054. if (!VisitedBBs.insert(IBB).second) {
  2055. NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
  2056. continue;
  2057. }
  2058. // Prepare the operand vector.
  2059. for (Value *V : E->Scalars)
  2060. Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
  2061. Builder.SetInsertPoint(IBB->getTerminator());
  2062. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  2063. Value *Vec = vectorizeTree(Operands);
  2064. NewPhi->addIncoming(Vec, IBB);
  2065. }
  2066. assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
  2067. "Invalid number of incoming values");
  2068. return NewPhi;
  2069. }
  2070. case Instruction::ExtractElement: {
  2071. if (canReuseExtract(E->Scalars, Instruction::ExtractElement)) {
  2072. Value *V = VL0->getOperand(0);
  2073. E->VectorizedValue = V;
  2074. return V;
  2075. }
  2076. setInsertPointAfterBundle(E->Scalars);
  2077. auto *V = Gather(E->Scalars, VecTy);
  2078. E->VectorizedValue = V;
  2079. return V;
  2080. }
  2081. case Instruction::ExtractValue: {
  2082. if (canReuseExtract(E->Scalars, Instruction::ExtractValue)) {
  2083. LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
  2084. Builder.SetInsertPoint(LI);
  2085. PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
  2086. Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
  2087. LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
  2088. E->VectorizedValue = V;
  2089. return propagateMetadata(V, E->Scalars);
  2090. }
  2091. setInsertPointAfterBundle(E->Scalars);
  2092. auto *V = Gather(E->Scalars, VecTy);
  2093. E->VectorizedValue = V;
  2094. return V;
  2095. }
  2096. case Instruction::ZExt:
  2097. case Instruction::SExt:
  2098. case Instruction::FPToUI:
  2099. case Instruction::FPToSI:
  2100. case Instruction::FPExt:
  2101. case Instruction::PtrToInt:
  2102. case Instruction::IntToPtr:
  2103. case Instruction::SIToFP:
  2104. case Instruction::UIToFP:
  2105. case Instruction::Trunc:
  2106. case Instruction::FPTrunc:
  2107. case Instruction::BitCast: {
  2108. ValueList INVL;
  2109. for (Value *V : E->Scalars)
  2110. INVL.push_back(cast<Instruction>(V)->getOperand(0));
  2111. setInsertPointAfterBundle(E->Scalars);
  2112. Value *InVec = vectorizeTree(INVL);
  2113. if (Value *V = alreadyVectorized(E->Scalars))
  2114. return V;
  2115. CastInst *CI = dyn_cast<CastInst>(VL0);
  2116. Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
  2117. E->VectorizedValue = V;
  2118. ++NumVectorInstructions;
  2119. return V;
  2120. }
  2121. case Instruction::FCmp:
  2122. case Instruction::ICmp: {
  2123. ValueList LHSV, RHSV;
  2124. for (Value *V : E->Scalars) {
  2125. LHSV.push_back(cast<Instruction>(V)->getOperand(0));
  2126. RHSV.push_back(cast<Instruction>(V)->getOperand(1));
  2127. }
  2128. setInsertPointAfterBundle(E->Scalars);
  2129. Value *L = vectorizeTree(LHSV);
  2130. Value *R = vectorizeTree(RHSV);
  2131. if (Value *V = alreadyVectorized(E->Scalars))
  2132. return V;
  2133. CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
  2134. Value *V;
  2135. if (Opcode == Instruction::FCmp)
  2136. V = Builder.CreateFCmp(P0, L, R);
  2137. else
  2138. V = Builder.CreateICmp(P0, L, R);
  2139. E->VectorizedValue = V;
  2140. propagateIRFlags(E->VectorizedValue, E->Scalars);
  2141. ++NumVectorInstructions;
  2142. return V;
  2143. }
  2144. case Instruction::Select: {
  2145. ValueList TrueVec, FalseVec, CondVec;
  2146. for (Value *V : E->Scalars) {
  2147. CondVec.push_back(cast<Instruction>(V)->getOperand(0));
  2148. TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
  2149. FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
  2150. }
  2151. setInsertPointAfterBundle(E->Scalars);
  2152. Value *Cond = vectorizeTree(CondVec);
  2153. Value *True = vectorizeTree(TrueVec);
  2154. Value *False = vectorizeTree(FalseVec);
  2155. if (Value *V = alreadyVectorized(E->Scalars))
  2156. return V;
  2157. Value *V = Builder.CreateSelect(Cond, True, False);
  2158. E->VectorizedValue = V;
  2159. ++NumVectorInstructions;
  2160. return V;
  2161. }
  2162. case Instruction::Add:
  2163. case Instruction::FAdd:
  2164. case Instruction::Sub:
  2165. case Instruction::FSub:
  2166. case Instruction::Mul:
  2167. case Instruction::FMul:
  2168. case Instruction::UDiv:
  2169. case Instruction::SDiv:
  2170. case Instruction::FDiv:
  2171. case Instruction::URem:
  2172. case Instruction::SRem:
  2173. case Instruction::FRem:
  2174. case Instruction::Shl:
  2175. case Instruction::LShr:
  2176. case Instruction::AShr:
  2177. case Instruction::And:
  2178. case Instruction::Or:
  2179. case Instruction::Xor: {
  2180. ValueList LHSVL, RHSVL;
  2181. if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
  2182. reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
  2183. else
  2184. for (Value *V : E->Scalars) {
  2185. LHSVL.push_back(cast<Instruction>(V)->getOperand(0));
  2186. RHSVL.push_back(cast<Instruction>(V)->getOperand(1));
  2187. }
  2188. setInsertPointAfterBundle(E->Scalars);
  2189. Value *LHS = vectorizeTree(LHSVL);
  2190. Value *RHS = vectorizeTree(RHSVL);
  2191. if (Value *V = alreadyVectorized(E->Scalars))
  2192. return V;
  2193. BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
  2194. Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
  2195. E->VectorizedValue = V;
  2196. propagateIRFlags(E->VectorizedValue, E->Scalars);
  2197. ++NumVectorInstructions;
  2198. if (Instruction *I = dyn_cast<Instruction>(V))
  2199. return propagateMetadata(I, E->Scalars);
  2200. return V;
  2201. }
  2202. case Instruction::Load: {
  2203. // Loads are inserted at the head of the tree because we don't want to
  2204. // sink them all the way down past store instructions.
  2205. setInsertPointAfterBundle(E->Scalars);
  2206. LoadInst *LI = cast<LoadInst>(VL0);
  2207. Type *ScalarLoadTy = LI->getType();
  2208. unsigned AS = LI->getPointerAddressSpace();
  2209. Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
  2210. VecTy->getPointerTo(AS));
  2211. // The pointer operand uses an in-tree scalar so we add the new BitCast to
  2212. // ExternalUses list to make sure that an extract will be generated in the
  2213. // future.
  2214. if (ScalarToTreeEntry.count(LI->getPointerOperand()))
  2215. ExternalUses.push_back(
  2216. ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
  2217. unsigned Alignment = LI->getAlignment();
  2218. LI = Builder.CreateLoad(VecPtr);
  2219. if (!Alignment) {
  2220. Alignment = DL->getABITypeAlignment(ScalarLoadTy);
  2221. }
  2222. LI->setAlignment(Alignment);
  2223. E->VectorizedValue = LI;
  2224. ++NumVectorInstructions;
  2225. return propagateMetadata(LI, E->Scalars);
  2226. }
  2227. case Instruction::Store: {
  2228. StoreInst *SI = cast<StoreInst>(VL0);
  2229. unsigned Alignment = SI->getAlignment();
  2230. unsigned AS = SI->getPointerAddressSpace();
  2231. ValueList ValueOp;
  2232. for (Value *V : E->Scalars)
  2233. ValueOp.push_back(cast<StoreInst>(V)->getValueOperand());
  2234. setInsertPointAfterBundle(E->Scalars);
  2235. Value *VecValue = vectorizeTree(ValueOp);
  2236. Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
  2237. VecTy->getPointerTo(AS));
  2238. StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
  2239. // The pointer operand uses an in-tree scalar so we add the new BitCast to
  2240. // ExternalUses list to make sure that an extract will be generated in the
  2241. // future.
  2242. if (ScalarToTreeEntry.count(SI->getPointerOperand()))
  2243. ExternalUses.push_back(
  2244. ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
  2245. if (!Alignment) {
  2246. Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
  2247. }
  2248. S->setAlignment(Alignment);
  2249. E->VectorizedValue = S;
  2250. ++NumVectorInstructions;
  2251. return propagateMetadata(S, E->Scalars);
  2252. }
  2253. case Instruction::GetElementPtr: {
  2254. setInsertPointAfterBundle(E->Scalars);
  2255. ValueList Op0VL;
  2256. for (Value *V : E->Scalars)
  2257. Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
  2258. Value *Op0 = vectorizeTree(Op0VL);
  2259. std::vector<Value *> OpVecs;
  2260. for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
  2261. ++j) {
  2262. ValueList OpVL;
  2263. for (Value *V : E->Scalars)
  2264. OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
  2265. Value *OpVec = vectorizeTree(OpVL);
  2266. OpVecs.push_back(OpVec);
  2267. }
  2268. Value *V = Builder.CreateGEP(
  2269. cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
  2270. E->VectorizedValue = V;
  2271. ++NumVectorInstructions;
  2272. if (Instruction *I = dyn_cast<Instruction>(V))
  2273. return propagateMetadata(I, E->Scalars);
  2274. return V;
  2275. }
  2276. case Instruction::Call: {
  2277. CallInst *CI = cast<CallInst>(VL0);
  2278. setInsertPointAfterBundle(E->Scalars);
  2279. Function *FI;
  2280. Intrinsic::ID IID = Intrinsic::not_intrinsic;
  2281. Value *ScalarArg = nullptr;
  2282. if (CI && (FI = CI->getCalledFunction())) {
  2283. IID = FI->getIntrinsicID();
  2284. }
  2285. std::vector<Value *> OpVecs;
  2286. for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
  2287. ValueList OpVL;
  2288. // ctlz,cttz and powi are special intrinsics whose second argument is
  2289. // a scalar. This argument should not be vectorized.
  2290. if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
  2291. CallInst *CEI = cast<CallInst>(E->Scalars[0]);
  2292. ScalarArg = CEI->getArgOperand(j);
  2293. OpVecs.push_back(CEI->getArgOperand(j));
  2294. continue;
  2295. }
  2296. for (Value *V : E->Scalars) {
  2297. CallInst *CEI = cast<CallInst>(V);
  2298. OpVL.push_back(CEI->getArgOperand(j));
  2299. }
  2300. Value *OpVec = vectorizeTree(OpVL);
  2301. DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
  2302. OpVecs.push_back(OpVec);
  2303. }
  2304. Module *M = F->getParent();
  2305. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  2306. Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
  2307. Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
  2308. SmallVector<OperandBundleDef, 1> OpBundles;
  2309. CI->getOperandBundlesAsDefs(OpBundles);
  2310. Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
  2311. // The scalar argument uses an in-tree scalar so we add the new vectorized
  2312. // call to ExternalUses list to make sure that an extract will be
  2313. // generated in the future.
  2314. if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
  2315. ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
  2316. E->VectorizedValue = V;
  2317. propagateIRFlags(E->VectorizedValue, E->Scalars);
  2318. ++NumVectorInstructions;
  2319. return V;
  2320. }
  2321. case Instruction::ShuffleVector: {
  2322. ValueList LHSVL, RHSVL;
  2323. assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand");
  2324. reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
  2325. setInsertPointAfterBundle(E->Scalars);
  2326. Value *LHS = vectorizeTree(LHSVL);
  2327. Value *RHS = vectorizeTree(RHSVL);
  2328. if (Value *V = alreadyVectorized(E->Scalars))
  2329. return V;
  2330. // Create a vector of LHS op1 RHS
  2331. BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
  2332. Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
  2333. // Create a vector of LHS op2 RHS
  2334. Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
  2335. BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
  2336. Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
  2337. // Create shuffle to take alternate operations from the vector.
  2338. // Also, gather up odd and even scalar ops to propagate IR flags to
  2339. // each vector operation.
  2340. ValueList OddScalars, EvenScalars;
  2341. unsigned e = E->Scalars.size();
  2342. SmallVector<Constant *, 8> Mask(e);
  2343. for (unsigned i = 0; i < e; ++i) {
  2344. if (i & 1) {
  2345. Mask[i] = Builder.getInt32(e + i);
  2346. OddScalars.push_back(E->Scalars[i]);
  2347. } else {
  2348. Mask[i] = Builder.getInt32(i);
  2349. EvenScalars.push_back(E->Scalars[i]);
  2350. }
  2351. }
  2352. Value *ShuffleMask = ConstantVector::get(Mask);
  2353. propagateIRFlags(V0, EvenScalars);
  2354. propagateIRFlags(V1, OddScalars);
  2355. Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
  2356. E->VectorizedValue = V;
  2357. ++NumVectorInstructions;
  2358. if (Instruction *I = dyn_cast<Instruction>(V))
  2359. return propagateMetadata(I, E->Scalars);
  2360. return V;
  2361. }
  2362. default:
  2363. llvm_unreachable("unknown inst");
  2364. }
  2365. return nullptr;
  2366. }
  2367. Value *BoUpSLP::vectorizeTree() {
  2368. // All blocks must be scheduled before any instructions are inserted.
  2369. for (auto &BSIter : BlocksSchedules) {
  2370. scheduleBlock(BSIter.second.get());
  2371. }
  2372. Builder.SetInsertPoint(&F->getEntryBlock().front());
  2373. auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
  2374. // If the vectorized tree can be rewritten in a smaller type, we truncate the
  2375. // vectorized root. InstCombine will then rewrite the entire expression. We
  2376. // sign extend the extracted values below.
  2377. auto *ScalarRoot = VectorizableTree[0].Scalars[0];
  2378. if (MinBWs.count(ScalarRoot)) {
  2379. if (auto *I = dyn_cast<Instruction>(VectorRoot))
  2380. Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
  2381. auto BundleWidth = VectorizableTree[0].Scalars.size();
  2382. auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
  2383. auto *VecTy = VectorType::get(MinTy, BundleWidth);
  2384. auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
  2385. VectorizableTree[0].VectorizedValue = Trunc;
  2386. }
  2387. DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
  2388. // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
  2389. // specified by ScalarType.
  2390. auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
  2391. if (!MinBWs.count(ScalarRoot))
  2392. return Ex;
  2393. if (MinBWs[ScalarRoot].second)
  2394. return Builder.CreateSExt(Ex, ScalarType);
  2395. return Builder.CreateZExt(Ex, ScalarType);
  2396. };
  2397. // Extract all of the elements with the external uses.
  2398. for (const auto &ExternalUse : ExternalUses) {
  2399. Value *Scalar = ExternalUse.Scalar;
  2400. llvm::User *User = ExternalUse.User;
  2401. // Skip users that we already RAUW. This happens when one instruction
  2402. // has multiple uses of the same value.
  2403. if (!is_contained(Scalar->users(), User))
  2404. continue;
  2405. assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
  2406. int Idx = ScalarToTreeEntry[Scalar];
  2407. TreeEntry *E = &VectorizableTree[Idx];
  2408. assert(!E->NeedToGather && "Extracting from a gather list");
  2409. Value *Vec = E->VectorizedValue;
  2410. assert(Vec && "Can't find vectorizable value");
  2411. Value *Lane = Builder.getInt32(ExternalUse.Lane);
  2412. // Generate extracts for out-of-tree users.
  2413. // Find the insertion point for the extractelement lane.
  2414. if (auto *VecI = dyn_cast<Instruction>(Vec)) {
  2415. if (PHINode *PH = dyn_cast<PHINode>(User)) {
  2416. for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
  2417. if (PH->getIncomingValue(i) == Scalar) {
  2418. TerminatorInst *IncomingTerminator =
  2419. PH->getIncomingBlock(i)->getTerminator();
  2420. if (isa<CatchSwitchInst>(IncomingTerminator)) {
  2421. Builder.SetInsertPoint(VecI->getParent(),
  2422. std::next(VecI->getIterator()));
  2423. } else {
  2424. Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
  2425. }
  2426. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  2427. Ex = extend(ScalarRoot, Ex, Scalar->getType());
  2428. CSEBlocks.insert(PH->getIncomingBlock(i));
  2429. PH->setOperand(i, Ex);
  2430. }
  2431. }
  2432. } else {
  2433. Builder.SetInsertPoint(cast<Instruction>(User));
  2434. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  2435. Ex = extend(ScalarRoot, Ex, Scalar->getType());
  2436. CSEBlocks.insert(cast<Instruction>(User)->getParent());
  2437. User->replaceUsesOfWith(Scalar, Ex);
  2438. }
  2439. } else {
  2440. Builder.SetInsertPoint(&F->getEntryBlock().front());
  2441. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  2442. Ex = extend(ScalarRoot, Ex, Scalar->getType());
  2443. CSEBlocks.insert(&F->getEntryBlock());
  2444. User->replaceUsesOfWith(Scalar, Ex);
  2445. }
  2446. DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
  2447. }
  2448. // For each vectorized value:
  2449. for (TreeEntry &EIdx : VectorizableTree) {
  2450. TreeEntry *Entry = &EIdx;
  2451. // For each lane:
  2452. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  2453. Value *Scalar = Entry->Scalars[Lane];
  2454. // No need to handle users of gathered values.
  2455. if (Entry->NeedToGather)
  2456. continue;
  2457. assert(Entry->VectorizedValue && "Can't find vectorizable value");
  2458. Type *Ty = Scalar->getType();
  2459. if (!Ty->isVoidTy()) {
  2460. #ifndef NDEBUG
  2461. for (User *U : Scalar->users()) {
  2462. DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
  2463. assert((ScalarToTreeEntry.count(U) ||
  2464. // It is legal to replace users in the ignorelist by undef.
  2465. is_contained(UserIgnoreList, U)) &&
  2466. "Replacing out-of-tree value with undef");
  2467. }
  2468. #endif
  2469. Value *Undef = UndefValue::get(Ty);
  2470. Scalar->replaceAllUsesWith(Undef);
  2471. }
  2472. DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
  2473. eraseInstruction(cast<Instruction>(Scalar));
  2474. }
  2475. }
  2476. Builder.ClearInsertionPoint();
  2477. return VectorizableTree[0].VectorizedValue;
  2478. }
  2479. void BoUpSLP::optimizeGatherSequence() {
  2480. DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
  2481. << " gather sequences instructions.\n");
  2482. // LICM InsertElementInst sequences.
  2483. for (Instruction *it : GatherSeq) {
  2484. InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
  2485. if (!Insert)
  2486. continue;
  2487. // Check if this block is inside a loop.
  2488. Loop *L = LI->getLoopFor(Insert->getParent());
  2489. if (!L)
  2490. continue;
  2491. // Check if it has a preheader.
  2492. BasicBlock *PreHeader = L->getLoopPreheader();
  2493. if (!PreHeader)
  2494. continue;
  2495. // If the vector or the element that we insert into it are
  2496. // instructions that are defined in this basic block then we can't
  2497. // hoist this instruction.
  2498. Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
  2499. Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
  2500. if (CurrVec && L->contains(CurrVec))
  2501. continue;
  2502. if (NewElem && L->contains(NewElem))
  2503. continue;
  2504. // We can hoist this instruction. Move it to the pre-header.
  2505. Insert->moveBefore(PreHeader->getTerminator());
  2506. }
  2507. // Make a list of all reachable blocks in our CSE queue.
  2508. SmallVector<const DomTreeNode *, 8> CSEWorkList;
  2509. CSEWorkList.reserve(CSEBlocks.size());
  2510. for (BasicBlock *BB : CSEBlocks)
  2511. if (DomTreeNode *N = DT->getNode(BB)) {
  2512. assert(DT->isReachableFromEntry(N));
  2513. CSEWorkList.push_back(N);
  2514. }
  2515. // Sort blocks by domination. This ensures we visit a block after all blocks
  2516. // dominating it are visited.
  2517. std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
  2518. [this](const DomTreeNode *A, const DomTreeNode *B) {
  2519. return DT->properlyDominates(A, B);
  2520. });
  2521. // Perform O(N^2) search over the gather sequences and merge identical
  2522. // instructions. TODO: We can further optimize this scan if we split the
  2523. // instructions into different buckets based on the insert lane.
  2524. SmallVector<Instruction *, 16> Visited;
  2525. for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
  2526. assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
  2527. "Worklist not sorted properly!");
  2528. BasicBlock *BB = (*I)->getBlock();
  2529. // For all instructions in blocks containing gather sequences:
  2530. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
  2531. Instruction *In = &*it++;
  2532. if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
  2533. continue;
  2534. // Check if we can replace this instruction with any of the
  2535. // visited instructions.
  2536. for (Instruction *v : Visited) {
  2537. if (In->isIdenticalTo(v) &&
  2538. DT->dominates(v->getParent(), In->getParent())) {
  2539. In->replaceAllUsesWith(v);
  2540. eraseInstruction(In);
  2541. In = nullptr;
  2542. break;
  2543. }
  2544. }
  2545. if (In) {
  2546. assert(!is_contained(Visited, In));
  2547. Visited.push_back(In);
  2548. }
  2549. }
  2550. }
  2551. CSEBlocks.clear();
  2552. GatherSeq.clear();
  2553. }
  2554. // Groups the instructions to a bundle (which is then a single scheduling entity)
  2555. // and schedules instructions until the bundle gets ready.
  2556. bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
  2557. BoUpSLP *SLP) {
  2558. if (isa<PHINode>(VL[0]))
  2559. return true;
  2560. // Initialize the instruction bundle.
  2561. Instruction *OldScheduleEnd = ScheduleEnd;
  2562. ScheduleData *PrevInBundle = nullptr;
  2563. ScheduleData *Bundle = nullptr;
  2564. bool ReSchedule = false;
  2565. DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
  2566. // Make sure that the scheduling region contains all
  2567. // instructions of the bundle.
  2568. for (Value *V : VL) {
  2569. if (!extendSchedulingRegion(V))
  2570. return false;
  2571. }
  2572. for (Value *V : VL) {
  2573. ScheduleData *BundleMember = getScheduleData(V);
  2574. assert(BundleMember &&
  2575. "no ScheduleData for bundle member (maybe not in same basic block)");
  2576. if (BundleMember->IsScheduled) {
  2577. // A bundle member was scheduled as single instruction before and now
  2578. // needs to be scheduled as part of the bundle. We just get rid of the
  2579. // existing schedule.
  2580. DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
  2581. << " was already scheduled\n");
  2582. ReSchedule = true;
  2583. }
  2584. assert(BundleMember->isSchedulingEntity() &&
  2585. "bundle member already part of other bundle");
  2586. if (PrevInBundle) {
  2587. PrevInBundle->NextInBundle = BundleMember;
  2588. } else {
  2589. Bundle = BundleMember;
  2590. }
  2591. BundleMember->UnscheduledDepsInBundle = 0;
  2592. Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
  2593. // Group the instructions to a bundle.
  2594. BundleMember->FirstInBundle = Bundle;
  2595. PrevInBundle = BundleMember;
  2596. }
  2597. if (ScheduleEnd != OldScheduleEnd) {
  2598. // The scheduling region got new instructions at the lower end (or it is a
  2599. // new region for the first bundle). This makes it necessary to
  2600. // recalculate all dependencies.
  2601. // It is seldom that this needs to be done a second time after adding the
  2602. // initial bundle to the region.
  2603. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  2604. ScheduleData *SD = getScheduleData(I);
  2605. SD->clearDependencies();
  2606. }
  2607. ReSchedule = true;
  2608. }
  2609. if (ReSchedule) {
  2610. resetSchedule();
  2611. initialFillReadyList(ReadyInsts);
  2612. }
  2613. DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
  2614. << BB->getName() << "\n");
  2615. calculateDependencies(Bundle, true, SLP);
  2616. // Now try to schedule the new bundle. As soon as the bundle is "ready" it
  2617. // means that there are no cyclic dependencies and we can schedule it.
  2618. // Note that's important that we don't "schedule" the bundle yet (see
  2619. // cancelScheduling).
  2620. while (!Bundle->isReady() && !ReadyInsts.empty()) {
  2621. ScheduleData *pickedSD = ReadyInsts.back();
  2622. ReadyInsts.pop_back();
  2623. if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
  2624. schedule(pickedSD, ReadyInsts);
  2625. }
  2626. }
  2627. if (!Bundle->isReady()) {
  2628. cancelScheduling(VL);
  2629. return false;
  2630. }
  2631. return true;
  2632. }
  2633. void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
  2634. if (isa<PHINode>(VL[0]))
  2635. return;
  2636. ScheduleData *Bundle = getScheduleData(VL[0]);
  2637. DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
  2638. assert(!Bundle->IsScheduled &&
  2639. "Can't cancel bundle which is already scheduled");
  2640. assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
  2641. "tried to unbundle something which is not a bundle");
  2642. // Un-bundle: make single instructions out of the bundle.
  2643. ScheduleData *BundleMember = Bundle;
  2644. while (BundleMember) {
  2645. assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
  2646. BundleMember->FirstInBundle = BundleMember;
  2647. ScheduleData *Next = BundleMember->NextInBundle;
  2648. BundleMember->NextInBundle = nullptr;
  2649. BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
  2650. if (BundleMember->UnscheduledDepsInBundle == 0) {
  2651. ReadyInsts.insert(BundleMember);
  2652. }
  2653. BundleMember = Next;
  2654. }
  2655. }
  2656. bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
  2657. if (getScheduleData(V))
  2658. return true;
  2659. Instruction *I = dyn_cast<Instruction>(V);
  2660. assert(I && "bundle member must be an instruction");
  2661. assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
  2662. if (!ScheduleStart) {
  2663. // It's the first instruction in the new region.
  2664. initScheduleData(I, I->getNextNode(), nullptr, nullptr);
  2665. ScheduleStart = I;
  2666. ScheduleEnd = I->getNextNode();
  2667. assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
  2668. DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
  2669. return true;
  2670. }
  2671. // Search up and down at the same time, because we don't know if the new
  2672. // instruction is above or below the existing scheduling region.
  2673. BasicBlock::reverse_iterator UpIter =
  2674. ++ScheduleStart->getIterator().getReverse();
  2675. BasicBlock::reverse_iterator UpperEnd = BB->rend();
  2676. BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
  2677. BasicBlock::iterator LowerEnd = BB->end();
  2678. for (;;) {
  2679. if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
  2680. DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
  2681. return false;
  2682. }
  2683. if (UpIter != UpperEnd) {
  2684. if (&*UpIter == I) {
  2685. initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
  2686. ScheduleStart = I;
  2687. DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
  2688. return true;
  2689. }
  2690. UpIter++;
  2691. }
  2692. if (DownIter != LowerEnd) {
  2693. if (&*DownIter == I) {
  2694. initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
  2695. nullptr);
  2696. ScheduleEnd = I->getNextNode();
  2697. assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
  2698. DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
  2699. return true;
  2700. }
  2701. DownIter++;
  2702. }
  2703. assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
  2704. "instruction not found in block");
  2705. }
  2706. return true;
  2707. }
  2708. void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
  2709. Instruction *ToI,
  2710. ScheduleData *PrevLoadStore,
  2711. ScheduleData *NextLoadStore) {
  2712. ScheduleData *CurrentLoadStore = PrevLoadStore;
  2713. for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
  2714. ScheduleData *SD = ScheduleDataMap[I];
  2715. if (!SD) {
  2716. // Allocate a new ScheduleData for the instruction.
  2717. if (ChunkPos >= ChunkSize) {
  2718. ScheduleDataChunks.push_back(
  2719. llvm::make_unique<ScheduleData[]>(ChunkSize));
  2720. ChunkPos = 0;
  2721. }
  2722. SD = &(ScheduleDataChunks.back()[ChunkPos++]);
  2723. ScheduleDataMap[I] = SD;
  2724. SD->Inst = I;
  2725. }
  2726. assert(!isInSchedulingRegion(SD) &&
  2727. "new ScheduleData already in scheduling region");
  2728. SD->init(SchedulingRegionID);
  2729. if (I->mayReadOrWriteMemory()) {
  2730. // Update the linked list of memory accessing instructions.
  2731. if (CurrentLoadStore) {
  2732. CurrentLoadStore->NextLoadStore = SD;
  2733. } else {
  2734. FirstLoadStoreInRegion = SD;
  2735. }
  2736. CurrentLoadStore = SD;
  2737. }
  2738. }
  2739. if (NextLoadStore) {
  2740. if (CurrentLoadStore)
  2741. CurrentLoadStore->NextLoadStore = NextLoadStore;
  2742. } else {
  2743. LastLoadStoreInRegion = CurrentLoadStore;
  2744. }
  2745. }
  2746. void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
  2747. bool InsertInReadyList,
  2748. BoUpSLP *SLP) {
  2749. assert(SD->isSchedulingEntity());
  2750. SmallVector<ScheduleData *, 10> WorkList;
  2751. WorkList.push_back(SD);
  2752. while (!WorkList.empty()) {
  2753. ScheduleData *SD = WorkList.back();
  2754. WorkList.pop_back();
  2755. ScheduleData *BundleMember = SD;
  2756. while (BundleMember) {
  2757. assert(isInSchedulingRegion(BundleMember));
  2758. if (!BundleMember->hasValidDependencies()) {
  2759. DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
  2760. BundleMember->Dependencies = 0;
  2761. BundleMember->resetUnscheduledDeps();
  2762. // Handle def-use chain dependencies.
  2763. for (User *U : BundleMember->Inst->users()) {
  2764. if (isa<Instruction>(U)) {
  2765. ScheduleData *UseSD = getScheduleData(U);
  2766. if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
  2767. BundleMember->Dependencies++;
  2768. ScheduleData *DestBundle = UseSD->FirstInBundle;
  2769. if (!DestBundle->IsScheduled) {
  2770. BundleMember->incrementUnscheduledDeps(1);
  2771. }
  2772. if (!DestBundle->hasValidDependencies()) {
  2773. WorkList.push_back(DestBundle);
  2774. }
  2775. }
  2776. } else {
  2777. // I'm not sure if this can ever happen. But we need to be safe.
  2778. // This lets the instruction/bundle never be scheduled and
  2779. // eventually disable vectorization.
  2780. BundleMember->Dependencies++;
  2781. BundleMember->incrementUnscheduledDeps(1);
  2782. }
  2783. }
  2784. // Handle the memory dependencies.
  2785. ScheduleData *DepDest = BundleMember->NextLoadStore;
  2786. if (DepDest) {
  2787. Instruction *SrcInst = BundleMember->Inst;
  2788. MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
  2789. bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
  2790. unsigned numAliased = 0;
  2791. unsigned DistToSrc = 1;
  2792. while (DepDest) {
  2793. assert(isInSchedulingRegion(DepDest));
  2794. // We have two limits to reduce the complexity:
  2795. // 1) AliasedCheckLimit: It's a small limit to reduce calls to
  2796. // SLP->isAliased (which is the expensive part in this loop).
  2797. // 2) MaxMemDepDistance: It's for very large blocks and it aborts
  2798. // the whole loop (even if the loop is fast, it's quadratic).
  2799. // It's important for the loop break condition (see below) to
  2800. // check this limit even between two read-only instructions.
  2801. if (DistToSrc >= MaxMemDepDistance ||
  2802. ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
  2803. (numAliased >= AliasedCheckLimit ||
  2804. SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
  2805. // We increment the counter only if the locations are aliased
  2806. // (instead of counting all alias checks). This gives a better
  2807. // balance between reduced runtime and accurate dependencies.
  2808. numAliased++;
  2809. DepDest->MemoryDependencies.push_back(BundleMember);
  2810. BundleMember->Dependencies++;
  2811. ScheduleData *DestBundle = DepDest->FirstInBundle;
  2812. if (!DestBundle->IsScheduled) {
  2813. BundleMember->incrementUnscheduledDeps(1);
  2814. }
  2815. if (!DestBundle->hasValidDependencies()) {
  2816. WorkList.push_back(DestBundle);
  2817. }
  2818. }
  2819. DepDest = DepDest->NextLoadStore;
  2820. // Example, explaining the loop break condition: Let's assume our
  2821. // starting instruction is i0 and MaxMemDepDistance = 3.
  2822. //
  2823. // +--------v--v--v
  2824. // i0,i1,i2,i3,i4,i5,i6,i7,i8
  2825. // +--------^--^--^
  2826. //
  2827. // MaxMemDepDistance let us stop alias-checking at i3 and we add
  2828. // dependencies from i0 to i3,i4,.. (even if they are not aliased).
  2829. // Previously we already added dependencies from i3 to i6,i7,i8
  2830. // (because of MaxMemDepDistance). As we added a dependency from
  2831. // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
  2832. // and we can abort this loop at i6.
  2833. if (DistToSrc >= 2 * MaxMemDepDistance)
  2834. break;
  2835. DistToSrc++;
  2836. }
  2837. }
  2838. }
  2839. BundleMember = BundleMember->NextInBundle;
  2840. }
  2841. if (InsertInReadyList && SD->isReady()) {
  2842. ReadyInsts.push_back(SD);
  2843. DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
  2844. }
  2845. }
  2846. }
  2847. void BoUpSLP::BlockScheduling::resetSchedule() {
  2848. assert(ScheduleStart &&
  2849. "tried to reset schedule on block which has not been scheduled");
  2850. for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  2851. ScheduleData *SD = getScheduleData(I);
  2852. assert(isInSchedulingRegion(SD));
  2853. SD->IsScheduled = false;
  2854. SD->resetUnscheduledDeps();
  2855. }
  2856. ReadyInsts.clear();
  2857. }
  2858. void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
  2859. if (!BS->ScheduleStart)
  2860. return;
  2861. DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
  2862. BS->resetSchedule();
  2863. // For the real scheduling we use a more sophisticated ready-list: it is
  2864. // sorted by the original instruction location. This lets the final schedule
  2865. // be as close as possible to the original instruction order.
  2866. struct ScheduleDataCompare {
  2867. bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
  2868. return SD2->SchedulingPriority < SD1->SchedulingPriority;
  2869. }
  2870. };
  2871. std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
  2872. // Ensure that all dependency data is updated and fill the ready-list with
  2873. // initial instructions.
  2874. int Idx = 0;
  2875. int NumToSchedule = 0;
  2876. for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
  2877. I = I->getNextNode()) {
  2878. ScheduleData *SD = BS->getScheduleData(I);
  2879. assert(
  2880. SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
  2881. "scheduler and vectorizer have different opinion on what is a bundle");
  2882. SD->FirstInBundle->SchedulingPriority = Idx++;
  2883. if (SD->isSchedulingEntity()) {
  2884. BS->calculateDependencies(SD, false, this);
  2885. NumToSchedule++;
  2886. }
  2887. }
  2888. BS->initialFillReadyList(ReadyInsts);
  2889. Instruction *LastScheduledInst = BS->ScheduleEnd;
  2890. // Do the "real" scheduling.
  2891. while (!ReadyInsts.empty()) {
  2892. ScheduleData *picked = *ReadyInsts.begin();
  2893. ReadyInsts.erase(ReadyInsts.begin());
  2894. // Move the scheduled instruction(s) to their dedicated places, if not
  2895. // there yet.
  2896. ScheduleData *BundleMember = picked;
  2897. while (BundleMember) {
  2898. Instruction *pickedInst = BundleMember->Inst;
  2899. if (LastScheduledInst->getNextNode() != pickedInst) {
  2900. BS->BB->getInstList().remove(pickedInst);
  2901. BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
  2902. pickedInst);
  2903. }
  2904. LastScheduledInst = pickedInst;
  2905. BundleMember = BundleMember->NextInBundle;
  2906. }
  2907. BS->schedule(picked, ReadyInsts);
  2908. NumToSchedule--;
  2909. }
  2910. assert(NumToSchedule == 0 && "could not schedule all instructions");
  2911. // Avoid duplicate scheduling of the block.
  2912. BS->ScheduleStart = nullptr;
  2913. }
  2914. unsigned BoUpSLP::getVectorElementSize(Value *V) {
  2915. // If V is a store, just return the width of the stored value without
  2916. // traversing the expression tree. This is the common case.
  2917. if (auto *Store = dyn_cast<StoreInst>(V))
  2918. return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
  2919. // If V is not a store, we can traverse the expression tree to find loads
  2920. // that feed it. The type of the loaded value may indicate a more suitable
  2921. // width than V's type. We want to base the vector element size on the width
  2922. // of memory operations where possible.
  2923. SmallVector<Instruction *, 16> Worklist;
  2924. SmallPtrSet<Instruction *, 16> Visited;
  2925. if (auto *I = dyn_cast<Instruction>(V))
  2926. Worklist.push_back(I);
  2927. // Traverse the expression tree in bottom-up order looking for loads. If we
  2928. // encounter an instruciton we don't yet handle, we give up.
  2929. auto MaxWidth = 0u;
  2930. auto FoundUnknownInst = false;
  2931. while (!Worklist.empty() && !FoundUnknownInst) {
  2932. auto *I = Worklist.pop_back_val();
  2933. Visited.insert(I);
  2934. // We should only be looking at scalar instructions here. If the current
  2935. // instruction has a vector type, give up.
  2936. auto *Ty = I->getType();
  2937. if (isa<VectorType>(Ty))
  2938. FoundUnknownInst = true;
  2939. // If the current instruction is a load, update MaxWidth to reflect the
  2940. // width of the loaded value.
  2941. else if (isa<LoadInst>(I))
  2942. MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
  2943. // Otherwise, we need to visit the operands of the instruction. We only
  2944. // handle the interesting cases from buildTree here. If an operand is an
  2945. // instruction we haven't yet visited, we add it to the worklist.
  2946. else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
  2947. isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
  2948. for (Use &U : I->operands())
  2949. if (auto *J = dyn_cast<Instruction>(U.get()))
  2950. if (!Visited.count(J))
  2951. Worklist.push_back(J);
  2952. }
  2953. // If we don't yet handle the instruction, give up.
  2954. else
  2955. FoundUnknownInst = true;
  2956. }
  2957. // If we didn't encounter a memory access in the expression tree, or if we
  2958. // gave up for some reason, just return the width of V.
  2959. if (!MaxWidth || FoundUnknownInst)
  2960. return DL->getTypeSizeInBits(V->getType());
  2961. // Otherwise, return the maximum width we found.
  2962. return MaxWidth;
  2963. }
  2964. // Determine if a value V in a vectorizable expression Expr can be demoted to a
  2965. // smaller type with a truncation. We collect the values that will be demoted
  2966. // in ToDemote and additional roots that require investigating in Roots.
  2967. static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
  2968. SmallVectorImpl<Value *> &ToDemote,
  2969. SmallVectorImpl<Value *> &Roots) {
  2970. // We can always demote constants.
  2971. if (isa<Constant>(V)) {
  2972. ToDemote.push_back(V);
  2973. return true;
  2974. }
  2975. // If the value is not an instruction in the expression with only one use, it
  2976. // cannot be demoted.
  2977. auto *I = dyn_cast<Instruction>(V);
  2978. if (!I || !I->hasOneUse() || !Expr.count(I))
  2979. return false;
  2980. switch (I->getOpcode()) {
  2981. // We can always demote truncations and extensions. Since truncations can
  2982. // seed additional demotion, we save the truncated value.
  2983. case Instruction::Trunc:
  2984. Roots.push_back(I->getOperand(0));
  2985. case Instruction::ZExt:
  2986. case Instruction::SExt:
  2987. break;
  2988. // We can demote certain binary operations if we can demote both of their
  2989. // operands.
  2990. case Instruction::Add:
  2991. case Instruction::Sub:
  2992. case Instruction::Mul:
  2993. case Instruction::And:
  2994. case Instruction::Or:
  2995. case Instruction::Xor:
  2996. if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
  2997. !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
  2998. return false;
  2999. break;
  3000. // We can demote selects if we can demote their true and false values.
  3001. case Instruction::Select: {
  3002. SelectInst *SI = cast<SelectInst>(I);
  3003. if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
  3004. !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
  3005. return false;
  3006. break;
  3007. }
  3008. // We can demote phis if we can demote all their incoming operands. Note that
  3009. // we don't need to worry about cycles since we ensure single use above.
  3010. case Instruction::PHI: {
  3011. PHINode *PN = cast<PHINode>(I);
  3012. for (Value *IncValue : PN->incoming_values())
  3013. if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
  3014. return false;
  3015. break;
  3016. }
  3017. // Otherwise, conservatively give up.
  3018. default:
  3019. return false;
  3020. }
  3021. // Record the value that we can demote.
  3022. ToDemote.push_back(V);
  3023. return true;
  3024. }
  3025. void BoUpSLP::computeMinimumValueSizes() {
  3026. // If there are no external uses, the expression tree must be rooted by a
  3027. // store. We can't demote in-memory values, so there is nothing to do here.
  3028. if (ExternalUses.empty())
  3029. return;
  3030. // We only attempt to truncate integer expressions.
  3031. auto &TreeRoot = VectorizableTree[0].Scalars;
  3032. auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
  3033. if (!TreeRootIT)
  3034. return;
  3035. // If the expression is not rooted by a store, these roots should have
  3036. // external uses. We will rely on InstCombine to rewrite the expression in
  3037. // the narrower type. However, InstCombine only rewrites single-use values.
  3038. // This means that if a tree entry other than a root is used externally, it
  3039. // must have multiple uses and InstCombine will not rewrite it. The code
  3040. // below ensures that only the roots are used externally.
  3041. SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
  3042. for (auto &EU : ExternalUses)
  3043. if (!Expr.erase(EU.Scalar))
  3044. return;
  3045. if (!Expr.empty())
  3046. return;
  3047. // Collect the scalar values of the vectorizable expression. We will use this
  3048. // context to determine which values can be demoted. If we see a truncation,
  3049. // we mark it as seeding another demotion.
  3050. for (auto &Entry : VectorizableTree)
  3051. Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
  3052. // Ensure the roots of the vectorizable tree don't form a cycle. They must
  3053. // have a single external user that is not in the vectorizable tree.
  3054. for (auto *Root : TreeRoot)
  3055. if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
  3056. return;
  3057. // Conservatively determine if we can actually truncate the roots of the
  3058. // expression. Collect the values that can be demoted in ToDemote and
  3059. // additional roots that require investigating in Roots.
  3060. SmallVector<Value *, 32> ToDemote;
  3061. SmallVector<Value *, 4> Roots;
  3062. for (auto *Root : TreeRoot)
  3063. if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
  3064. return;
  3065. // The maximum bit width required to represent all the values that can be
  3066. // demoted without loss of precision. It would be safe to truncate the roots
  3067. // of the expression to this width.
  3068. auto MaxBitWidth = 8u;
  3069. // We first check if all the bits of the roots are demanded. If they're not,
  3070. // we can truncate the roots to this narrower type.
  3071. for (auto *Root : TreeRoot) {
  3072. auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
  3073. MaxBitWidth = std::max<unsigned>(
  3074. Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
  3075. }
  3076. // True if the roots can be zero-extended back to their original type, rather
  3077. // than sign-extended. We know that if the leading bits are not demanded, we
  3078. // can safely zero-extend. So we initialize IsKnownPositive to True.
  3079. bool IsKnownPositive = true;
  3080. // If all the bits of the roots are demanded, we can try a little harder to
  3081. // compute a narrower type. This can happen, for example, if the roots are
  3082. // getelementptr indices. InstCombine promotes these indices to the pointer
  3083. // width. Thus, all their bits are technically demanded even though the
  3084. // address computation might be vectorized in a smaller type.
  3085. //
  3086. // We start by looking at each entry that can be demoted. We compute the
  3087. // maximum bit width required to store the scalar by using ValueTracking to
  3088. // compute the number of high-order bits we can truncate.
  3089. if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
  3090. MaxBitWidth = 8u;
  3091. // Determine if the sign bit of all the roots is known to be zero. If not,
  3092. // IsKnownPositive is set to False.
  3093. IsKnownPositive = all_of(TreeRoot, [&](Value *R) {
  3094. bool KnownZero = false;
  3095. bool KnownOne = false;
  3096. ComputeSignBit(R, KnownZero, KnownOne, *DL);
  3097. return KnownZero;
  3098. });
  3099. // Determine the maximum number of bits required to store the scalar
  3100. // values.
  3101. for (auto *Scalar : ToDemote) {
  3102. auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, 0, DT);
  3103. auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
  3104. MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
  3105. }
  3106. // If we can't prove that the sign bit is zero, we must add one to the
  3107. // maximum bit width to account for the unknown sign bit. This preserves
  3108. // the existing sign bit so we can safely sign-extend the root back to the
  3109. // original type. Otherwise, if we know the sign bit is zero, we will
  3110. // zero-extend the root instead.
  3111. //
  3112. // FIXME: This is somewhat suboptimal, as there will be cases where adding
  3113. // one to the maximum bit width will yield a larger-than-necessary
  3114. // type. In general, we need to add an extra bit only if we can't
  3115. // prove that the upper bit of the original type is equal to the
  3116. // upper bit of the proposed smaller type. If these two bits are the
  3117. // same (either zero or one) we know that sign-extending from the
  3118. // smaller type will result in the same value. Here, since we can't
  3119. // yet prove this, we are just making the proposed smaller type
  3120. // larger to ensure correctness.
  3121. if (!IsKnownPositive)
  3122. ++MaxBitWidth;
  3123. }
  3124. // Round MaxBitWidth up to the next power-of-two.
  3125. if (!isPowerOf2_64(MaxBitWidth))
  3126. MaxBitWidth = NextPowerOf2(MaxBitWidth);
  3127. // If the maximum bit width we compute is less than the with of the roots'
  3128. // type, we can proceed with the narrowing. Otherwise, do nothing.
  3129. if (MaxBitWidth >= TreeRootIT->getBitWidth())
  3130. return;
  3131. // If we can truncate the root, we must collect additional values that might
  3132. // be demoted as a result. That is, those seeded by truncations we will
  3133. // modify.
  3134. while (!Roots.empty())
  3135. collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
  3136. // Finally, map the values we can demote to the maximum bit with we computed.
  3137. for (auto *Scalar : ToDemote)
  3138. MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
  3139. }
  3140. namespace {
  3141. /// The SLPVectorizer Pass.
  3142. struct SLPVectorizer : public FunctionPass {
  3143. SLPVectorizerPass Impl;
  3144. /// Pass identification, replacement for typeid
  3145. static char ID;
  3146. explicit SLPVectorizer() : FunctionPass(ID) {
  3147. initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
  3148. }
  3149. bool doInitialization(Module &M) override {
  3150. return false;
  3151. }
  3152. bool runOnFunction(Function &F) override {
  3153. if (skipFunction(F))
  3154. return false;
  3155. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  3156. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  3157. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  3158. auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
  3159. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  3160. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  3161. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  3162. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  3163. auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  3164. return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB);
  3165. }
  3166. void getAnalysisUsage(AnalysisUsage &AU) const override {
  3167. FunctionPass::getAnalysisUsage(AU);
  3168. AU.addRequired<AssumptionCacheTracker>();
  3169. AU.addRequired<ScalarEvolutionWrapperPass>();
  3170. AU.addRequired<AAResultsWrapperPass>();
  3171. AU.addRequired<TargetTransformInfoWrapperPass>();
  3172. AU.addRequired<LoopInfoWrapperPass>();
  3173. AU.addRequired<DominatorTreeWrapperPass>();
  3174. AU.addRequired<DemandedBitsWrapperPass>();
  3175. AU.addPreserved<LoopInfoWrapperPass>();
  3176. AU.addPreserved<DominatorTreeWrapperPass>();
  3177. AU.addPreserved<AAResultsWrapperPass>();
  3178. AU.addPreserved<GlobalsAAWrapperPass>();
  3179. AU.setPreservesCFG();
  3180. }
  3181. };
  3182. } // end anonymous namespace
  3183. PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
  3184. auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
  3185. auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
  3186. auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
  3187. auto *AA = &AM.getResult<AAManager>(F);
  3188. auto *LI = &AM.getResult<LoopAnalysis>(F);
  3189. auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
  3190. auto *AC = &AM.getResult<AssumptionAnalysis>(F);
  3191. auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
  3192. bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB);
  3193. if (!Changed)
  3194. return PreservedAnalyses::all();
  3195. PreservedAnalyses PA;
  3196. PA.preserveSet<CFGAnalyses>();
  3197. PA.preserve<AAManager>();
  3198. PA.preserve<GlobalsAA>();
  3199. return PA;
  3200. }
  3201. bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
  3202. TargetTransformInfo *TTI_,
  3203. TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
  3204. LoopInfo *LI_, DominatorTree *DT_,
  3205. AssumptionCache *AC_, DemandedBits *DB_) {
  3206. SE = SE_;
  3207. TTI = TTI_;
  3208. TLI = TLI_;
  3209. AA = AA_;
  3210. LI = LI_;
  3211. DT = DT_;
  3212. AC = AC_;
  3213. DB = DB_;
  3214. DL = &F.getParent()->getDataLayout();
  3215. Stores.clear();
  3216. GEPs.clear();
  3217. bool Changed = false;
  3218. // If the target claims to have no vector registers don't attempt
  3219. // vectorization.
  3220. if (!TTI->getNumberOfRegisters(true))
  3221. return false;
  3222. // Don't vectorize when the attribute NoImplicitFloat is used.
  3223. if (F.hasFnAttribute(Attribute::NoImplicitFloat))
  3224. return false;
  3225. DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
  3226. // Use the bottom up slp vectorizer to construct chains that start with
  3227. // store instructions.
  3228. BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL);
  3229. // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
  3230. // delete instructions.
  3231. // Scan the blocks in the function in post order.
  3232. for (auto BB : post_order(&F.getEntryBlock())) {
  3233. collectSeedInstructions(BB);
  3234. // Vectorize trees that end at stores.
  3235. if (!Stores.empty()) {
  3236. DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
  3237. << " underlying objects.\n");
  3238. Changed |= vectorizeStoreChains(R);
  3239. }
  3240. // Vectorize trees that end at reductions.
  3241. Changed |= vectorizeChainsInBlock(BB, R);
  3242. // Vectorize the index computations of getelementptr instructions. This
  3243. // is primarily intended to catch gather-like idioms ending at
  3244. // non-consecutive loads.
  3245. if (!GEPs.empty()) {
  3246. DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
  3247. << " underlying objects.\n");
  3248. Changed |= vectorizeGEPIndices(BB, R);
  3249. }
  3250. }
  3251. if (Changed) {
  3252. R.optimizeGatherSequence();
  3253. DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
  3254. DEBUG(verifyFunction(F));
  3255. }
  3256. return Changed;
  3257. }
  3258. /// \brief Check that the Values in the slice in VL array are still existent in
  3259. /// the WeakVH array.
  3260. /// Vectorization of part of the VL array may cause later values in the VL array
  3261. /// to become invalid. We track when this has happened in the WeakVH array.
  3262. static bool hasValueBeenRAUWed(ArrayRef<Value *> VL, ArrayRef<WeakVH> VH,
  3263. unsigned SliceBegin, unsigned SliceSize) {
  3264. VL = VL.slice(SliceBegin, SliceSize);
  3265. VH = VH.slice(SliceBegin, SliceSize);
  3266. return !std::equal(VL.begin(), VL.end(), VH.begin());
  3267. }
  3268. bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
  3269. unsigned VecRegSize) {
  3270. unsigned ChainLen = Chain.size();
  3271. DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
  3272. << "\n");
  3273. unsigned Sz = R.getVectorElementSize(Chain[0]);
  3274. unsigned VF = VecRegSize / Sz;
  3275. if (!isPowerOf2_32(Sz) || VF < 2)
  3276. return false;
  3277. // Keep track of values that were deleted by vectorizing in the loop below.
  3278. SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
  3279. bool Changed = false;
  3280. // Look for profitable vectorizable trees at all offsets, starting at zero.
  3281. for (unsigned i = 0, e = ChainLen; i < e; ++i) {
  3282. if (i + VF > e)
  3283. break;
  3284. // Check that a previous iteration of this loop did not delete the Value.
  3285. if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
  3286. continue;
  3287. DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
  3288. << "\n");
  3289. ArrayRef<Value *> Operands = Chain.slice(i, VF);
  3290. R.buildTree(Operands);
  3291. if (R.isTreeTinyAndNotFullyVectorizable())
  3292. continue;
  3293. R.computeMinimumValueSizes();
  3294. int Cost = R.getTreeCost();
  3295. DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
  3296. if (Cost < -SLPCostThreshold) {
  3297. DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
  3298. R.vectorizeTree();
  3299. // Move to the next bundle.
  3300. i += VF - 1;
  3301. Changed = true;
  3302. }
  3303. }
  3304. return Changed;
  3305. }
  3306. bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
  3307. BoUpSLP &R) {
  3308. SetVector<StoreInst *> Heads, Tails;
  3309. SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
  3310. // We may run into multiple chains that merge into a single chain. We mark the
  3311. // stores that we vectorized so that we don't visit the same store twice.
  3312. BoUpSLP::ValueSet VectorizedStores;
  3313. bool Changed = false;
  3314. // Do a quadratic search on all of the given stores and find
  3315. // all of the pairs of stores that follow each other.
  3316. SmallVector<unsigned, 16> IndexQueue;
  3317. for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
  3318. IndexQueue.clear();
  3319. // If a store has multiple consecutive store candidates, search Stores
  3320. // array according to the sequence: from i+1 to e, then from i-1 to 0.
  3321. // This is because usually pairing with immediate succeeding or preceding
  3322. // candidate create the best chance to find slp vectorization opportunity.
  3323. unsigned j = 0;
  3324. for (j = i + 1; j < e; ++j)
  3325. IndexQueue.push_back(j);
  3326. for (j = i; j > 0; --j)
  3327. IndexQueue.push_back(j - 1);
  3328. for (auto &k : IndexQueue) {
  3329. if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
  3330. Tails.insert(Stores[k]);
  3331. Heads.insert(Stores[i]);
  3332. ConsecutiveChain[Stores[i]] = Stores[k];
  3333. break;
  3334. }
  3335. }
  3336. }
  3337. // For stores that start but don't end a link in the chain:
  3338. for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
  3339. it != e; ++it) {
  3340. if (Tails.count(*it))
  3341. continue;
  3342. // We found a store instr that starts a chain. Now follow the chain and try
  3343. // to vectorize it.
  3344. BoUpSLP::ValueList Operands;
  3345. StoreInst *I = *it;
  3346. // Collect the chain into a list.
  3347. while (Tails.count(I) || Heads.count(I)) {
  3348. if (VectorizedStores.count(I))
  3349. break;
  3350. Operands.push_back(I);
  3351. // Move to the next value in the chain.
  3352. I = ConsecutiveChain[I];
  3353. }
  3354. // FIXME: Is division-by-2 the correct step? Should we assert that the
  3355. // register size is a power-of-2?
  3356. for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
  3357. Size /= 2) {
  3358. if (vectorizeStoreChain(Operands, R, Size)) {
  3359. // Mark the vectorized stores so that we don't vectorize them again.
  3360. VectorizedStores.insert(Operands.begin(), Operands.end());
  3361. Changed = true;
  3362. break;
  3363. }
  3364. }
  3365. }
  3366. return Changed;
  3367. }
  3368. void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
  3369. // Initialize the collections. We will make a single pass over the block.
  3370. Stores.clear();
  3371. GEPs.clear();
  3372. // Visit the store and getelementptr instructions in BB and organize them in
  3373. // Stores and GEPs according to the underlying objects of their pointer
  3374. // operands.
  3375. for (Instruction &I : *BB) {
  3376. // Ignore store instructions that are volatile or have a pointer operand
  3377. // that doesn't point to a scalar type.
  3378. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  3379. if (!SI->isSimple())
  3380. continue;
  3381. if (!isValidElementType(SI->getValueOperand()->getType()))
  3382. continue;
  3383. Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
  3384. }
  3385. // Ignore getelementptr instructions that have more than one index, a
  3386. // constant index, or a pointer operand that doesn't point to a scalar
  3387. // type.
  3388. else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  3389. auto Idx = GEP->idx_begin()->get();
  3390. if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
  3391. continue;
  3392. if (!isValidElementType(Idx->getType()))
  3393. continue;
  3394. if (GEP->getType()->isVectorTy())
  3395. continue;
  3396. GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
  3397. }
  3398. }
  3399. }
  3400. bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
  3401. if (!A || !B)
  3402. return false;
  3403. Value *VL[] = { A, B };
  3404. return tryToVectorizeList(VL, R, None, true);
  3405. }
  3406. bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
  3407. ArrayRef<Value *> BuildVector,
  3408. bool AllowReorder) {
  3409. if (VL.size() < 2)
  3410. return false;
  3411. DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size()
  3412. << ".\n");
  3413. // Check that all of the parts are scalar instructions of the same type.
  3414. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  3415. if (!I0)
  3416. return false;
  3417. unsigned Opcode0 = I0->getOpcode();
  3418. unsigned Sz = R.getVectorElementSize(I0);
  3419. unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
  3420. unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
  3421. if (MaxVF < 2)
  3422. return false;
  3423. for (Value *V : VL) {
  3424. Type *Ty = V->getType();
  3425. if (!isValidElementType(Ty))
  3426. return false;
  3427. Instruction *Inst = dyn_cast<Instruction>(V);
  3428. if (!Inst || Inst->getOpcode() != Opcode0)
  3429. return false;
  3430. }
  3431. bool Changed = false;
  3432. // Keep track of values that were deleted by vectorizing in the loop below.
  3433. SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
  3434. unsigned NextInst = 0, MaxInst = VL.size();
  3435. for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
  3436. VF /= 2) {
  3437. // No actual vectorization should happen, if number of parts is the same as
  3438. // provided vectorization factor (i.e. the scalar type is used for vector
  3439. // code during codegen).
  3440. auto *VecTy = VectorType::get(VL[0]->getType(), VF);
  3441. if (TTI->getNumberOfParts(VecTy) == VF)
  3442. continue;
  3443. for (unsigned I = NextInst; I < MaxInst; ++I) {
  3444. unsigned OpsWidth = 0;
  3445. if (I + VF > MaxInst)
  3446. OpsWidth = MaxInst - I;
  3447. else
  3448. OpsWidth = VF;
  3449. if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
  3450. break;
  3451. // Check that a previous iteration of this loop did not delete the Value.
  3452. if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
  3453. continue;
  3454. DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
  3455. << "\n");
  3456. ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
  3457. ArrayRef<Value *> BuildVectorSlice;
  3458. if (!BuildVector.empty())
  3459. BuildVectorSlice = BuildVector.slice(I, OpsWidth);
  3460. R.buildTree(Ops, BuildVectorSlice);
  3461. // TODO: check if we can allow reordering for more cases.
  3462. if (AllowReorder && R.shouldReorder()) {
  3463. // Conceptually, there is nothing actually preventing us from trying to
  3464. // reorder a larger list. In fact, we do exactly this when vectorizing
  3465. // reductions. However, at this point, we only expect to get here from
  3466. // tryToVectorizePair().
  3467. assert(Ops.size() == 2);
  3468. assert(BuildVectorSlice.empty());
  3469. Value *ReorderedOps[] = {Ops[1], Ops[0]};
  3470. R.buildTree(ReorderedOps, None);
  3471. }
  3472. if (R.isTreeTinyAndNotFullyVectorizable())
  3473. continue;
  3474. R.computeMinimumValueSizes();
  3475. int Cost = R.getTreeCost();
  3476. if (Cost < -SLPCostThreshold) {
  3477. DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
  3478. Value *VectorizedRoot = R.vectorizeTree();
  3479. // Reconstruct the build vector by extracting the vectorized root. This
  3480. // way we handle the case where some elements of the vector are
  3481. // undefined.
  3482. // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
  3483. if (!BuildVectorSlice.empty()) {
  3484. // The insert point is the last build vector instruction. The
  3485. // vectorized root will precede it. This guarantees that we get an
  3486. // instruction. The vectorized tree could have been constant folded.
  3487. Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
  3488. unsigned VecIdx = 0;
  3489. for (auto &V : BuildVectorSlice) {
  3490. IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
  3491. ++BasicBlock::iterator(InsertAfter));
  3492. Instruction *I = cast<Instruction>(V);
  3493. assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
  3494. Instruction *Extract =
  3495. cast<Instruction>(Builder.CreateExtractElement(
  3496. VectorizedRoot, Builder.getInt32(VecIdx++)));
  3497. I->setOperand(1, Extract);
  3498. I->removeFromParent();
  3499. I->insertAfter(Extract);
  3500. InsertAfter = I;
  3501. }
  3502. }
  3503. // Move to the next bundle.
  3504. I += VF - 1;
  3505. NextInst = I + 1;
  3506. Changed = true;
  3507. }
  3508. }
  3509. }
  3510. return Changed;
  3511. }
  3512. bool SLPVectorizerPass::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
  3513. if (!V)
  3514. return false;
  3515. Value *P = V->getParent();
  3516. // Vectorize in current basic block only.
  3517. auto *Op0 = dyn_cast<Instruction>(V->getOperand(0));
  3518. auto *Op1 = dyn_cast<Instruction>(V->getOperand(1));
  3519. if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
  3520. return false;
  3521. // Try to vectorize V.
  3522. if (tryToVectorizePair(Op0, Op1, R))
  3523. return true;
  3524. auto *A = dyn_cast<BinaryOperator>(Op0);
  3525. auto *B = dyn_cast<BinaryOperator>(Op1);
  3526. // Try to skip B.
  3527. if (B && B->hasOneUse()) {
  3528. auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
  3529. auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
  3530. if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
  3531. return true;
  3532. if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
  3533. return true;
  3534. }
  3535. // Try to skip A.
  3536. if (A && A->hasOneUse()) {
  3537. auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
  3538. auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
  3539. if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
  3540. return true;
  3541. if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
  3542. return true;
  3543. }
  3544. return false;
  3545. }
  3546. /// \brief Generate a shuffle mask to be used in a reduction tree.
  3547. ///
  3548. /// \param VecLen The length of the vector to be reduced.
  3549. /// \param NumEltsToRdx The number of elements that should be reduced in the
  3550. /// vector.
  3551. /// \param IsPairwise Whether the reduction is a pairwise or splitting
  3552. /// reduction. A pairwise reduction will generate a mask of
  3553. /// <0,2,...> or <1,3,..> while a splitting reduction will generate
  3554. /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
  3555. /// \param IsLeft True will generate a mask of even elements, odd otherwise.
  3556. static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
  3557. bool IsPairwise, bool IsLeft,
  3558. IRBuilder<> &Builder) {
  3559. assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
  3560. SmallVector<Constant *, 32> ShuffleMask(
  3561. VecLen, UndefValue::get(Builder.getInt32Ty()));
  3562. if (IsPairwise)
  3563. // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
  3564. for (unsigned i = 0; i != NumEltsToRdx; ++i)
  3565. ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
  3566. else
  3567. // Move the upper half of the vector to the lower half.
  3568. for (unsigned i = 0; i != NumEltsToRdx; ++i)
  3569. ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
  3570. return ConstantVector::get(ShuffleMask);
  3571. }
  3572. namespace {
  3573. /// Model horizontal reductions.
  3574. ///
  3575. /// A horizontal reduction is a tree of reduction operations (currently add and
  3576. /// fadd) that has operations that can be put into a vector as its leaf.
  3577. /// For example, this tree:
  3578. ///
  3579. /// mul mul mul mul
  3580. /// \ / \ /
  3581. /// + +
  3582. /// \ /
  3583. /// +
  3584. /// This tree has "mul" as its reduced values and "+" as its reduction
  3585. /// operations. A reduction might be feeding into a store or a binary operation
  3586. /// feeding a phi.
  3587. /// ...
  3588. /// \ /
  3589. /// +
  3590. /// |
  3591. /// phi +=
  3592. ///
  3593. /// Or:
  3594. /// ...
  3595. /// \ /
  3596. /// +
  3597. /// |
  3598. /// *p =
  3599. ///
  3600. class HorizontalReduction {
  3601. SmallVector<Value *, 16> ReductionOps;
  3602. SmallVector<Value *, 32> ReducedVals;
  3603. BinaryOperator *ReductionRoot;
  3604. // After successfull horizontal reduction vectorization attempt for PHI node
  3605. // vectorizer tries to update root binary op by combining vectorized tree and
  3606. // the ReductionPHI node. But during vectorization this ReductionPHI can be
  3607. // vectorized itself and replaced by the undef value, while the instruction
  3608. // itself is marked for deletion. This 'marked for deletion' PHI node then can
  3609. // be used in new binary operation, causing "Use still stuck around after Def
  3610. // is destroyed" crash upon PHI node deletion.
  3611. WeakVH ReductionPHI;
  3612. /// The opcode of the reduction.
  3613. unsigned ReductionOpcode;
  3614. /// The opcode of the values we perform a reduction on.
  3615. unsigned ReducedValueOpcode;
  3616. /// Should we model this reduction as a pairwise reduction tree or a tree that
  3617. /// splits the vector in halves and adds those halves.
  3618. bool IsPairwiseReduction;
  3619. public:
  3620. /// The width of one full horizontal reduction operation.
  3621. unsigned ReduxWidth;
  3622. /// Minimal width of available vector registers. It's used to determine
  3623. /// ReduxWidth.
  3624. unsigned MinVecRegSize;
  3625. HorizontalReduction(unsigned MinVecRegSize)
  3626. : ReductionRoot(nullptr), ReductionOpcode(0), ReducedValueOpcode(0),
  3627. IsPairwiseReduction(false), ReduxWidth(0),
  3628. MinVecRegSize(MinVecRegSize) {}
  3629. /// \brief Try to find a reduction tree.
  3630. bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
  3631. assert((!Phi || is_contained(Phi->operands(), B)) &&
  3632. "Thi phi needs to use the binary operator");
  3633. // We could have a initial reductions that is not an add.
  3634. // r *= v1 + v2 + v3 + v4
  3635. // In such a case start looking for a tree rooted in the first '+'.
  3636. if (Phi) {
  3637. if (B->getOperand(0) == Phi) {
  3638. Phi = nullptr;
  3639. B = dyn_cast<BinaryOperator>(B->getOperand(1));
  3640. } else if (B->getOperand(1) == Phi) {
  3641. Phi = nullptr;
  3642. B = dyn_cast<BinaryOperator>(B->getOperand(0));
  3643. }
  3644. }
  3645. if (!B)
  3646. return false;
  3647. Type *Ty = B->getType();
  3648. if (!isValidElementType(Ty))
  3649. return false;
  3650. const DataLayout &DL = B->getModule()->getDataLayout();
  3651. ReductionOpcode = B->getOpcode();
  3652. ReducedValueOpcode = 0;
  3653. // FIXME: Register size should be a parameter to this function, so we can
  3654. // try different vectorization factors.
  3655. ReduxWidth = MinVecRegSize / DL.getTypeSizeInBits(Ty);
  3656. ReductionRoot = B;
  3657. ReductionPHI = Phi;
  3658. if (ReduxWidth < 4)
  3659. return false;
  3660. // We currently only support adds.
  3661. if (ReductionOpcode != Instruction::Add &&
  3662. ReductionOpcode != Instruction::FAdd)
  3663. return false;
  3664. // Post order traverse the reduction tree starting at B. We only handle true
  3665. // trees containing only binary operators or selects.
  3666. SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
  3667. Stack.push_back(std::make_pair(B, 0));
  3668. while (!Stack.empty()) {
  3669. Instruction *TreeN = Stack.back().first;
  3670. unsigned EdgeToVist = Stack.back().second++;
  3671. bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
  3672. // Only handle trees in the current basic block.
  3673. if (TreeN->getParent() != B->getParent())
  3674. return false;
  3675. // Each tree node needs to have one user except for the ultimate
  3676. // reduction.
  3677. if (!TreeN->hasOneUse() && TreeN != B)
  3678. return false;
  3679. // Postorder vist.
  3680. if (EdgeToVist == 2 || IsReducedValue) {
  3681. if (IsReducedValue) {
  3682. // Make sure that the opcodes of the operations that we are going to
  3683. // reduce match.
  3684. if (!ReducedValueOpcode)
  3685. ReducedValueOpcode = TreeN->getOpcode();
  3686. else if (ReducedValueOpcode != TreeN->getOpcode())
  3687. return false;
  3688. ReducedVals.push_back(TreeN);
  3689. } else {
  3690. // We need to be able to reassociate the adds.
  3691. if (!TreeN->isAssociative())
  3692. return false;
  3693. ReductionOps.push_back(TreeN);
  3694. }
  3695. // Retract.
  3696. Stack.pop_back();
  3697. continue;
  3698. }
  3699. // Visit left or right.
  3700. Value *NextV = TreeN->getOperand(EdgeToVist);
  3701. if (NextV != Phi) {
  3702. auto *I = dyn_cast<Instruction>(NextV);
  3703. // Continue analysis if the next operand is a reduction operation or
  3704. // (possibly) a reduced value. If the reduced value opcode is not set,
  3705. // the first met operation != reduction operation is considered as the
  3706. // reduced value class.
  3707. if (I && (!ReducedValueOpcode || I->getOpcode() == ReducedValueOpcode ||
  3708. I->getOpcode() == ReductionOpcode)) {
  3709. if (!ReducedValueOpcode && I->getOpcode() != ReductionOpcode)
  3710. ReducedValueOpcode = I->getOpcode();
  3711. Stack.push_back(std::make_pair(I, 0));
  3712. continue;
  3713. }
  3714. return false;
  3715. }
  3716. }
  3717. return true;
  3718. }
  3719. /// \brief Attempt to vectorize the tree found by
  3720. /// matchAssociativeReduction.
  3721. bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
  3722. if (ReducedVals.empty())
  3723. return false;
  3724. unsigned NumReducedVals = ReducedVals.size();
  3725. if (NumReducedVals < ReduxWidth)
  3726. return false;
  3727. Value *VectorizedTree = nullptr;
  3728. IRBuilder<> Builder(ReductionRoot);
  3729. FastMathFlags Unsafe;
  3730. Unsafe.setUnsafeAlgebra();
  3731. Builder.setFastMathFlags(Unsafe);
  3732. unsigned i = 0;
  3733. for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
  3734. auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
  3735. V.buildTree(VL, ReductionOps);
  3736. if (V.shouldReorder()) {
  3737. SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
  3738. V.buildTree(Reversed, ReductionOps);
  3739. }
  3740. if (V.isTreeTinyAndNotFullyVectorizable())
  3741. continue;
  3742. V.computeMinimumValueSizes();
  3743. // Estimate cost.
  3744. int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
  3745. if (Cost >= -SLPCostThreshold)
  3746. break;
  3747. DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
  3748. << ". (HorRdx)\n");
  3749. // Vectorize a tree.
  3750. DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
  3751. Value *VectorizedRoot = V.vectorizeTree();
  3752. // Emit a reduction.
  3753. Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
  3754. if (VectorizedTree) {
  3755. Builder.SetCurrentDebugLocation(Loc);
  3756. VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
  3757. ReducedSubTree, "bin.rdx");
  3758. } else
  3759. VectorizedTree = ReducedSubTree;
  3760. }
  3761. if (VectorizedTree) {
  3762. // Finish the reduction.
  3763. for (; i < NumReducedVals; ++i) {
  3764. Builder.SetCurrentDebugLocation(
  3765. cast<Instruction>(ReducedVals[i])->getDebugLoc());
  3766. VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
  3767. ReducedVals[i]);
  3768. }
  3769. // Update users.
  3770. if (ReductionPHI && !isa<UndefValue>(ReductionPHI)) {
  3771. assert(ReductionRoot && "Need a reduction operation");
  3772. ReductionRoot->setOperand(0, VectorizedTree);
  3773. ReductionRoot->setOperand(1, ReductionPHI);
  3774. } else
  3775. ReductionRoot->replaceAllUsesWith(VectorizedTree);
  3776. }
  3777. return VectorizedTree != nullptr;
  3778. }
  3779. unsigned numReductionValues() const {
  3780. return ReducedVals.size();
  3781. }
  3782. private:
  3783. /// \brief Calculate the cost of a reduction.
  3784. int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
  3785. Type *ScalarTy = FirstReducedVal->getType();
  3786. Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
  3787. int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
  3788. int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
  3789. IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
  3790. int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
  3791. int ScalarReduxCost =
  3792. (ReduxWidth - 1) *
  3793. TTI->getArithmeticInstrCost(ReductionOpcode, ScalarTy);
  3794. DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
  3795. << " for reduction that starts with " << *FirstReducedVal
  3796. << " (It is a "
  3797. << (IsPairwiseReduction ? "pairwise" : "splitting")
  3798. << " reduction)\n");
  3799. return VecReduxCost - ScalarReduxCost;
  3800. }
  3801. static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
  3802. Value *R, const Twine &Name = "") {
  3803. if (Opcode == Instruction::FAdd)
  3804. return Builder.CreateFAdd(L, R, Name);
  3805. return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
  3806. }
  3807. /// \brief Emit a horizontal reduction of the vectorized value.
  3808. Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
  3809. assert(VectorizedValue && "Need to have a vectorized tree node");
  3810. assert(isPowerOf2_32(ReduxWidth) &&
  3811. "We only handle power-of-two reductions for now");
  3812. Value *TmpVec = VectorizedValue;
  3813. for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
  3814. if (IsPairwiseReduction) {
  3815. Value *LeftMask =
  3816. createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
  3817. Value *RightMask =
  3818. createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
  3819. Value *LeftShuf = Builder.CreateShuffleVector(
  3820. TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
  3821. Value *RightShuf = Builder.CreateShuffleVector(
  3822. TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
  3823. "rdx.shuf.r");
  3824. TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
  3825. "bin.rdx");
  3826. } else {
  3827. Value *UpperHalf =
  3828. createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
  3829. Value *Shuf = Builder.CreateShuffleVector(
  3830. TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
  3831. TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
  3832. }
  3833. }
  3834. // The result is in the first element of the vector.
  3835. return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
  3836. }
  3837. };
  3838. } // end anonymous namespace
  3839. /// \brief Recognize construction of vectors like
  3840. /// %ra = insertelement <4 x float> undef, float %s0, i32 0
  3841. /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
  3842. /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
  3843. /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
  3844. ///
  3845. /// Returns true if it matches
  3846. ///
  3847. static bool findBuildVector(InsertElementInst *FirstInsertElem,
  3848. SmallVectorImpl<Value *> &BuildVector,
  3849. SmallVectorImpl<Value *> &BuildVectorOpds) {
  3850. if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
  3851. return false;
  3852. InsertElementInst *IE = FirstInsertElem;
  3853. while (true) {
  3854. BuildVector.push_back(IE);
  3855. BuildVectorOpds.push_back(IE->getOperand(1));
  3856. if (IE->use_empty())
  3857. return false;
  3858. InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
  3859. if (!NextUse)
  3860. return true;
  3861. // If this isn't the final use, make sure the next insertelement is the only
  3862. // use. It's OK if the final constructed vector is used multiple times
  3863. if (!IE->hasOneUse())
  3864. return false;
  3865. IE = NextUse;
  3866. }
  3867. return false;
  3868. }
  3869. /// \brief Like findBuildVector, but looks backwards for construction of aggregate.
  3870. ///
  3871. /// \return true if it matches.
  3872. static bool findBuildAggregate(InsertValueInst *IV,
  3873. SmallVectorImpl<Value *> &BuildVector,
  3874. SmallVectorImpl<Value *> &BuildVectorOpds) {
  3875. if (!IV->hasOneUse())
  3876. return false;
  3877. Value *V = IV->getAggregateOperand();
  3878. if (!isa<UndefValue>(V)) {
  3879. InsertValueInst *I = dyn_cast<InsertValueInst>(V);
  3880. if (!I || !findBuildAggregate(I, BuildVector, BuildVectorOpds))
  3881. return false;
  3882. }
  3883. BuildVector.push_back(IV);
  3884. BuildVectorOpds.push_back(IV->getInsertedValueOperand());
  3885. return true;
  3886. }
  3887. static bool PhiTypeSorterFunc(Value *V, Value *V2) {
  3888. return V->getType() < V2->getType();
  3889. }
  3890. /// \brief Try and get a reduction value from a phi node.
  3891. ///
  3892. /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
  3893. /// if they come from either \p ParentBB or a containing loop latch.
  3894. ///
  3895. /// \returns A candidate reduction value if possible, or \code nullptr \endcode
  3896. /// if not possible.
  3897. static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
  3898. BasicBlock *ParentBB, LoopInfo *LI) {
  3899. // There are situations where the reduction value is not dominated by the
  3900. // reduction phi. Vectorizing such cases has been reported to cause
  3901. // miscompiles. See PR25787.
  3902. auto DominatedReduxValue = [&](Value *R) {
  3903. return (
  3904. dyn_cast<Instruction>(R) &&
  3905. DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
  3906. };
  3907. Value *Rdx = nullptr;
  3908. // Return the incoming value if it comes from the same BB as the phi node.
  3909. if (P->getIncomingBlock(0) == ParentBB) {
  3910. Rdx = P->getIncomingValue(0);
  3911. } else if (P->getIncomingBlock(1) == ParentBB) {
  3912. Rdx = P->getIncomingValue(1);
  3913. }
  3914. if (Rdx && DominatedReduxValue(Rdx))
  3915. return Rdx;
  3916. // Otherwise, check whether we have a loop latch to look at.
  3917. Loop *BBL = LI->getLoopFor(ParentBB);
  3918. if (!BBL)
  3919. return nullptr;
  3920. BasicBlock *BBLatch = BBL->getLoopLatch();
  3921. if (!BBLatch)
  3922. return nullptr;
  3923. // There is a loop latch, return the incoming value if it comes from
  3924. // that. This reduction pattern occasionally turns up.
  3925. if (P->getIncomingBlock(0) == BBLatch) {
  3926. Rdx = P->getIncomingValue(0);
  3927. } else if (P->getIncomingBlock(1) == BBLatch) {
  3928. Rdx = P->getIncomingValue(1);
  3929. }
  3930. if (Rdx && DominatedReduxValue(Rdx))
  3931. return Rdx;
  3932. return nullptr;
  3933. }
  3934. namespace {
  3935. /// Tracks instructons and its children.
  3936. class WeakVHWithLevel final : public CallbackVH {
  3937. /// Operand index of the instruction currently beeing analized.
  3938. unsigned Level = 0;
  3939. /// Is this the instruction that should be vectorized, or are we now
  3940. /// processing children (i.e. operands of this instruction) for potential
  3941. /// vectorization?
  3942. bool IsInitial = true;
  3943. public:
  3944. explicit WeakVHWithLevel() = default;
  3945. WeakVHWithLevel(Value *V) : CallbackVH(V){};
  3946. /// Restart children analysis each time it is repaced by the new instruction.
  3947. void allUsesReplacedWith(Value *New) override {
  3948. setValPtr(New);
  3949. Level = 0;
  3950. IsInitial = true;
  3951. }
  3952. /// Check if the instruction was not deleted during vectorization.
  3953. bool isValid() const { return !getValPtr(); }
  3954. /// Is the istruction itself must be vectorized?
  3955. bool isInitial() const { return IsInitial; }
  3956. /// Try to vectorize children.
  3957. void clearInitial() { IsInitial = false; }
  3958. /// Are all children processed already?
  3959. bool isFinal() const {
  3960. assert(getValPtr() &&
  3961. (isa<Instruction>(getValPtr()) &&
  3962. cast<Instruction>(getValPtr())->getNumOperands() >= Level));
  3963. return getValPtr() &&
  3964. cast<Instruction>(getValPtr())->getNumOperands() == Level;
  3965. }
  3966. /// Get next child operation.
  3967. Value *nextOperand() {
  3968. assert(getValPtr() && isa<Instruction>(getValPtr()) &&
  3969. cast<Instruction>(getValPtr())->getNumOperands() > Level);
  3970. return cast<Instruction>(getValPtr())->getOperand(Level++);
  3971. }
  3972. virtual ~WeakVHWithLevel() = default;
  3973. };
  3974. } // namespace
  3975. /// \brief Attempt to reduce a horizontal reduction.
  3976. /// If it is legal to match a horizontal reduction feeding
  3977. /// the phi node P with reduction operators Root in a basic block BB, then check
  3978. /// if it can be done.
  3979. /// \returns true if a horizontal reduction was matched and reduced.
  3980. /// \returns false if a horizontal reduction was not matched.
  3981. static bool canBeVectorized(
  3982. PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
  3983. TargetTransformInfo *TTI,
  3984. const function_ref<bool(BinaryOperator *, BoUpSLP &)> Vectorize) {
  3985. if (!ShouldVectorizeHor)
  3986. return false;
  3987. if (!Root)
  3988. return false;
  3989. if (Root->getParent() != BB)
  3990. return false;
  3991. SmallVector<WeakVHWithLevel, 8> Stack(1, Root);
  3992. SmallSet<Value *, 8> VisitedInstrs;
  3993. bool Res = false;
  3994. while (!Stack.empty()) {
  3995. Value *V = Stack.back();
  3996. if (!V) {
  3997. Stack.pop_back();
  3998. continue;
  3999. }
  4000. auto *Inst = dyn_cast<Instruction>(V);
  4001. if (!Inst || isa<PHINode>(Inst)) {
  4002. Stack.pop_back();
  4003. continue;
  4004. }
  4005. if (Stack.back().isInitial()) {
  4006. Stack.back().clearInitial();
  4007. if (auto *BI = dyn_cast<BinaryOperator>(Inst)) {
  4008. HorizontalReduction HorRdx(R.getMinVecRegSize());
  4009. if (HorRdx.matchAssociativeReduction(P, BI)) {
  4010. // If there is a sufficient number of reduction values, reduce
  4011. // to a nearby power-of-2. Can safely generate oversized
  4012. // vectors and rely on the backend to split them to legal sizes.
  4013. HorRdx.ReduxWidth =
  4014. std::max((uint64_t)4, PowerOf2Floor(HorRdx.numReductionValues()));
  4015. if (HorRdx.tryToReduce(R, TTI)) {
  4016. Res = true;
  4017. P = nullptr;
  4018. continue;
  4019. }
  4020. }
  4021. if (P) {
  4022. Inst = dyn_cast<Instruction>(BI->getOperand(0));
  4023. if (Inst == P)
  4024. Inst = dyn_cast<Instruction>(BI->getOperand(1));
  4025. if (!Inst) {
  4026. P = nullptr;
  4027. continue;
  4028. }
  4029. }
  4030. }
  4031. P = nullptr;
  4032. if (Vectorize(dyn_cast<BinaryOperator>(Inst), R)) {
  4033. Res = true;
  4034. continue;
  4035. }
  4036. }
  4037. if (Stack.back().isFinal()) {
  4038. Stack.pop_back();
  4039. continue;
  4040. }
  4041. if (auto *NextV = dyn_cast<Instruction>(Stack.back().nextOperand()))
  4042. if (NextV->getParent() == BB && VisitedInstrs.insert(NextV).second &&
  4043. Stack.size() < RecursionMaxDepth)
  4044. Stack.push_back(NextV);
  4045. }
  4046. return Res;
  4047. }
  4048. bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
  4049. BasicBlock *BB, BoUpSLP &R,
  4050. TargetTransformInfo *TTI) {
  4051. if (!V)
  4052. return false;
  4053. auto *I = dyn_cast<Instruction>(V);
  4054. if (!I)
  4055. return false;
  4056. if (!isa<BinaryOperator>(I))
  4057. P = nullptr;
  4058. // Try to match and vectorize a horizontal reduction.
  4059. return canBeVectorized(P, I, BB, R, TTI,
  4060. [this](BinaryOperator *BI, BoUpSLP &R) -> bool {
  4061. return tryToVectorize(BI, R);
  4062. });
  4063. }
  4064. bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
  4065. bool Changed = false;
  4066. SmallVector<Value *, 4> Incoming;
  4067. SmallSet<Value *, 16> VisitedInstrs;
  4068. bool HaveVectorizedPhiNodes = true;
  4069. while (HaveVectorizedPhiNodes) {
  4070. HaveVectorizedPhiNodes = false;
  4071. // Collect the incoming values from the PHIs.
  4072. Incoming.clear();
  4073. for (Instruction &I : *BB) {
  4074. PHINode *P = dyn_cast<PHINode>(&I);
  4075. if (!P)
  4076. break;
  4077. if (!VisitedInstrs.count(P))
  4078. Incoming.push_back(P);
  4079. }
  4080. // Sort by type.
  4081. std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
  4082. // Try to vectorize elements base on their type.
  4083. for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
  4084. E = Incoming.end();
  4085. IncIt != E;) {
  4086. // Look for the next elements with the same type.
  4087. SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
  4088. while (SameTypeIt != E &&
  4089. (*SameTypeIt)->getType() == (*IncIt)->getType()) {
  4090. VisitedInstrs.insert(*SameTypeIt);
  4091. ++SameTypeIt;
  4092. }
  4093. // Try to vectorize them.
  4094. unsigned NumElts = (SameTypeIt - IncIt);
  4095. DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
  4096. if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
  4097. // Success start over because instructions might have been changed.
  4098. HaveVectorizedPhiNodes = true;
  4099. Changed = true;
  4100. break;
  4101. }
  4102. // Start over at the next instruction of a different type (or the end).
  4103. IncIt = SameTypeIt;
  4104. }
  4105. }
  4106. VisitedInstrs.clear();
  4107. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
  4108. // We may go through BB multiple times so skip the one we have checked.
  4109. if (!VisitedInstrs.insert(&*it).second)
  4110. continue;
  4111. if (isa<DbgInfoIntrinsic>(it))
  4112. continue;
  4113. // Try to vectorize reductions that use PHINodes.
  4114. if (PHINode *P = dyn_cast<PHINode>(it)) {
  4115. // Check that the PHI is a reduction PHI.
  4116. if (P->getNumIncomingValues() != 2)
  4117. return Changed;
  4118. // Try to match and vectorize a horizontal reduction.
  4119. if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
  4120. TTI)) {
  4121. Changed = true;
  4122. it = BB->begin();
  4123. e = BB->end();
  4124. continue;
  4125. }
  4126. continue;
  4127. }
  4128. if (ShouldStartVectorizeHorAtStore) {
  4129. if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
  4130. // Try to match and vectorize a horizontal reduction.
  4131. if (vectorizeRootInstruction(nullptr, SI->getValueOperand(), BB, R,
  4132. TTI)) {
  4133. Changed = true;
  4134. it = BB->begin();
  4135. e = BB->end();
  4136. continue;
  4137. }
  4138. }
  4139. }
  4140. // Try to vectorize horizontal reductions feeding into a return.
  4141. if (ReturnInst *RI = dyn_cast<ReturnInst>(it)) {
  4142. if (RI->getNumOperands() != 0) {
  4143. // Try to match and vectorize a horizontal reduction.
  4144. if (vectorizeRootInstruction(nullptr, RI->getOperand(0), BB, R, TTI)) {
  4145. Changed = true;
  4146. it = BB->begin();
  4147. e = BB->end();
  4148. continue;
  4149. }
  4150. }
  4151. }
  4152. // Try to vectorize trees that start at compare instructions.
  4153. if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
  4154. if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
  4155. Changed = true;
  4156. // We would like to start over since some instructions are deleted
  4157. // and the iterator may become invalid value.
  4158. it = BB->begin();
  4159. e = BB->end();
  4160. continue;
  4161. }
  4162. for (int I = 0; I < 2; ++I) {
  4163. if (vectorizeRootInstruction(nullptr, CI->getOperand(I), BB, R, TTI)) {
  4164. Changed = true;
  4165. // We would like to start over since some instructions are deleted
  4166. // and the iterator may become invalid value.
  4167. it = BB->begin();
  4168. e = BB->end();
  4169. break;
  4170. }
  4171. }
  4172. continue;
  4173. }
  4174. // Try to vectorize trees that start at insertelement instructions.
  4175. if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
  4176. SmallVector<Value *, 16> BuildVector;
  4177. SmallVector<Value *, 16> BuildVectorOpds;
  4178. if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
  4179. continue;
  4180. // Vectorize starting with the build vector operands ignoring the
  4181. // BuildVector instructions for the purpose of scheduling and user
  4182. // extraction.
  4183. if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
  4184. Changed = true;
  4185. it = BB->begin();
  4186. e = BB->end();
  4187. }
  4188. continue;
  4189. }
  4190. // Try to vectorize trees that start at insertvalue instructions feeding into
  4191. // a store.
  4192. if (StoreInst *SI = dyn_cast<StoreInst>(it)) {
  4193. if (InsertValueInst *LastInsertValue = dyn_cast<InsertValueInst>(SI->getValueOperand())) {
  4194. const DataLayout &DL = BB->getModule()->getDataLayout();
  4195. if (R.canMapToVector(SI->getValueOperand()->getType(), DL)) {
  4196. SmallVector<Value *, 16> BuildVector;
  4197. SmallVector<Value *, 16> BuildVectorOpds;
  4198. if (!findBuildAggregate(LastInsertValue, BuildVector, BuildVectorOpds))
  4199. continue;
  4200. DEBUG(dbgs() << "SLP: store of array mappable to vector: " << *SI << "\n");
  4201. if (tryToVectorizeList(BuildVectorOpds, R, BuildVector, false)) {
  4202. Changed = true;
  4203. it = BB->begin();
  4204. e = BB->end();
  4205. }
  4206. continue;
  4207. }
  4208. }
  4209. }
  4210. }
  4211. return Changed;
  4212. }
  4213. bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
  4214. auto Changed = false;
  4215. for (auto &Entry : GEPs) {
  4216. // If the getelementptr list has fewer than two elements, there's nothing
  4217. // to do.
  4218. if (Entry.second.size() < 2)
  4219. continue;
  4220. DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
  4221. << Entry.second.size() << ".\n");
  4222. // We process the getelementptr list in chunks of 16 (like we do for
  4223. // stores) to minimize compile-time.
  4224. for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
  4225. auto Len = std::min<unsigned>(BE - BI, 16);
  4226. auto GEPList = makeArrayRef(&Entry.second[BI], Len);
  4227. // Initialize a set a candidate getelementptrs. Note that we use a
  4228. // SetVector here to preserve program order. If the index computations
  4229. // are vectorizable and begin with loads, we want to minimize the chance
  4230. // of having to reorder them later.
  4231. SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
  4232. // Some of the candidates may have already been vectorized after we
  4233. // initially collected them. If so, the WeakVHs will have nullified the
  4234. // values, so remove them from the set of candidates.
  4235. Candidates.remove(nullptr);
  4236. // Remove from the set of candidates all pairs of getelementptrs with
  4237. // constant differences. Such getelementptrs are likely not good
  4238. // candidates for vectorization in a bottom-up phase since one can be
  4239. // computed from the other. We also ensure all candidate getelementptr
  4240. // indices are unique.
  4241. for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
  4242. auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
  4243. if (!Candidates.count(GEPI))
  4244. continue;
  4245. auto *SCEVI = SE->getSCEV(GEPList[I]);
  4246. for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
  4247. auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
  4248. auto *SCEVJ = SE->getSCEV(GEPList[J]);
  4249. if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
  4250. Candidates.remove(GEPList[I]);
  4251. Candidates.remove(GEPList[J]);
  4252. } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
  4253. Candidates.remove(GEPList[J]);
  4254. }
  4255. }
  4256. }
  4257. // We break out of the above computation as soon as we know there are
  4258. // fewer than two candidates remaining.
  4259. if (Candidates.size() < 2)
  4260. continue;
  4261. // Add the single, non-constant index of each candidate to the bundle. We
  4262. // ensured the indices met these constraints when we originally collected
  4263. // the getelementptrs.
  4264. SmallVector<Value *, 16> Bundle(Candidates.size());
  4265. auto BundleIndex = 0u;
  4266. for (auto *V : Candidates) {
  4267. auto *GEP = cast<GetElementPtrInst>(V);
  4268. auto *GEPIdx = GEP->idx_begin()->get();
  4269. assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
  4270. Bundle[BundleIndex++] = GEPIdx;
  4271. }
  4272. // Try and vectorize the indices. We are currently only interested in
  4273. // gather-like cases of the form:
  4274. //
  4275. // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
  4276. //
  4277. // where the loads of "a", the loads of "b", and the subtractions can be
  4278. // performed in parallel. It's likely that detecting this pattern in a
  4279. // bottom-up phase will be simpler and less costly than building a
  4280. // full-blown top-down phase beginning at the consecutive loads.
  4281. Changed |= tryToVectorizeList(Bundle, R);
  4282. }
  4283. }
  4284. return Changed;
  4285. }
  4286. bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
  4287. bool Changed = false;
  4288. // Attempt to sort and vectorize each of the store-groups.
  4289. for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
  4290. ++it) {
  4291. if (it->second.size() < 2)
  4292. continue;
  4293. DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
  4294. << it->second.size() << ".\n");
  4295. // Process the stores in chunks of 16.
  4296. // TODO: The limit of 16 inhibits greater vectorization factors.
  4297. // For example, AVX2 supports v32i8. Increasing this limit, however,
  4298. // may cause a significant compile-time increase.
  4299. for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
  4300. unsigned Len = std::min<unsigned>(CE - CI, 16);
  4301. Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
  4302. }
  4303. }
  4304. return Changed;
  4305. }
  4306. char SLPVectorizer::ID = 0;
  4307. static const char lv_name[] = "SLP Vectorizer";
  4308. INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
  4309. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  4310. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  4311. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  4312. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  4313. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  4314. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  4315. INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
  4316. namespace llvm {
  4317. Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
  4318. }