SLPVectorizer.cpp 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020
  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.h"
  19. #include "llvm/ADT/MapVector.h"
  20. #include "llvm/ADT/PostOrderIterator.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/Optional.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/Analysis/AliasAnalysis.h"
  25. #include "llvm/Analysis/AssumptionCache.h"
  26. #include "llvm/Analysis/CodeMetrics.h"
  27. #include "llvm/Analysis/LoopInfo.h"
  28. #include "llvm/Analysis/ScalarEvolution.h"
  29. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  30. #include "llvm/Analysis/TargetTransformInfo.h"
  31. #include "llvm/Analysis/ValueTracking.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/Dominators.h"
  34. #include "llvm/IR/IRBuilder.h"
  35. #include "llvm/IR/Instructions.h"
  36. #include "llvm/IR/IntrinsicInst.h"
  37. #include "llvm/IR/Module.h"
  38. #include "llvm/IR/NoFolder.h"
  39. #include "llvm/IR/Type.h"
  40. #include "llvm/IR/Value.h"
  41. #include "llvm/IR/Verifier.h"
  42. #include "llvm/Pass.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/Debug.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include "llvm/Transforms/Utils/VectorUtils.h"
  47. #include <algorithm>
  48. #include <map>
  49. #include <memory>
  50. using namespace llvm;
  51. #define SV_NAME "slp-vectorizer"
  52. #define DEBUG_TYPE "SLP"
  53. STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
  54. static cl::opt<int>
  55. SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
  56. cl::desc("Only vectorize if you gain more than this "
  57. "number "));
  58. static cl::opt<bool>
  59. ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
  60. cl::desc("Attempt to vectorize horizontal reductions"));
  61. static cl::opt<bool> ShouldStartVectorizeHorAtStore(
  62. "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
  63. cl::desc(
  64. "Attempt to vectorize horizontal reductions feeding into a store"));
  65. namespace {
  66. static const unsigned MinVecRegSize = 128;
  67. static const unsigned RecursionMaxDepth = 12;
  68. // Limit the number of alias checks. The limit is chosen so that
  69. // it has no negative effect on the llvm benchmarks.
  70. static const unsigned AliasedCheckLimit = 10;
  71. // Another limit for the alias checks: The maximum distance between load/store
  72. // instructions where alias checks are done.
  73. // This limit is useful for very large basic blocks.
  74. static const unsigned MaxMemDepDistance = 160;
  75. /// \brief Predicate for the element types that the SLP vectorizer supports.
  76. ///
  77. /// The most important thing to filter here are types which are invalid in LLVM
  78. /// vectors. We also filter target specific types which have absolutely no
  79. /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
  80. /// avoids spending time checking the cost model and realizing that they will
  81. /// be inevitably scalarized.
  82. static bool isValidElementType(Type *Ty) {
  83. return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
  84. !Ty->isPPC_FP128Ty();
  85. }
  86. /// \returns the parent basic block if all of the instructions in \p VL
  87. /// are in the same block or null otherwise.
  88. static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
  89. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  90. if (!I0)
  91. return nullptr;
  92. BasicBlock *BB = I0->getParent();
  93. for (int i = 1, e = VL.size(); i < e; i++) {
  94. Instruction *I = dyn_cast<Instruction>(VL[i]);
  95. if (!I)
  96. return nullptr;
  97. if (BB != I->getParent())
  98. return nullptr;
  99. }
  100. return BB;
  101. }
  102. /// \returns True if all of the values in \p VL are constants.
  103. static bool allConstant(ArrayRef<Value *> VL) {
  104. for (unsigned i = 0, e = VL.size(); i < e; ++i)
  105. if (!isa<Constant>(VL[i]))
  106. return false;
  107. return true;
  108. }
  109. /// \returns True if all of the values in \p VL are identical.
  110. static bool isSplat(ArrayRef<Value *> VL) {
  111. for (unsigned i = 1, e = VL.size(); i < e; ++i)
  112. if (VL[i] != VL[0])
  113. return false;
  114. return true;
  115. }
  116. ///\returns Opcode that can be clubbed with \p Op to create an alternate
  117. /// sequence which can later be merged as a ShuffleVector instruction.
  118. static unsigned getAltOpcode(unsigned Op) {
  119. switch (Op) {
  120. case Instruction::FAdd:
  121. return Instruction::FSub;
  122. case Instruction::FSub:
  123. return Instruction::FAdd;
  124. case Instruction::Add:
  125. return Instruction::Sub;
  126. case Instruction::Sub:
  127. return Instruction::Add;
  128. default:
  129. return 0;
  130. }
  131. }
  132. ///\returns bool representing if Opcode \p Op can be part
  133. /// of an alternate sequence which can later be merged as
  134. /// a ShuffleVector instruction.
  135. static bool canCombineAsAltInst(unsigned Op) {
  136. if (Op == Instruction::FAdd || Op == Instruction::FSub ||
  137. Op == Instruction::Sub || Op == Instruction::Add)
  138. return true;
  139. return false;
  140. }
  141. /// \returns ShuffleVector instruction if intructions in \p VL have
  142. /// alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
  143. /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
  144. static unsigned isAltInst(ArrayRef<Value *> VL) {
  145. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  146. unsigned Opcode = I0->getOpcode();
  147. unsigned AltOpcode = getAltOpcode(Opcode);
  148. for (int i = 1, e = VL.size(); i < e; i++) {
  149. Instruction *I = dyn_cast<Instruction>(VL[i]);
  150. if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
  151. return 0;
  152. }
  153. return Instruction::ShuffleVector;
  154. }
  155. /// \returns The opcode if all of the Instructions in \p VL have the same
  156. /// opcode, or zero.
  157. static unsigned getSameOpcode(ArrayRef<Value *> VL) {
  158. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  159. if (!I0)
  160. return 0;
  161. unsigned Opcode = I0->getOpcode();
  162. for (int i = 1, e = VL.size(); i < e; i++) {
  163. Instruction *I = dyn_cast<Instruction>(VL[i]);
  164. if (!I || Opcode != I->getOpcode()) {
  165. if (canCombineAsAltInst(Opcode) && i == 1)
  166. return isAltInst(VL);
  167. return 0;
  168. }
  169. }
  170. return Opcode;
  171. }
  172. /// Get the intersection (logical and) of all of the potential IR flags
  173. /// of each scalar operation (VL) that will be converted into a vector (I).
  174. /// Flag set: NSW, NUW, exact, and all of fast-math.
  175. static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
  176. if (auto *VecOp = dyn_cast<BinaryOperator>(I)) {
  177. if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) {
  178. // Intersection is initialized to the 0th scalar,
  179. // so start counting from index '1'.
  180. for (int i = 1, e = VL.size(); i < e; ++i) {
  181. if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i]))
  182. Intersection->andIRFlags(Scalar);
  183. }
  184. VecOp->copyIRFlags(Intersection);
  185. }
  186. }
  187. }
  188. /// \returns \p I after propagating metadata from \p VL.
  189. static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
  190. Instruction *I0 = cast<Instruction>(VL[0]);
  191. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  192. I0->getAllMetadataOtherThanDebugLoc(Metadata);
  193. for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
  194. unsigned Kind = Metadata[i].first;
  195. MDNode *MD = Metadata[i].second;
  196. for (int i = 1, e = VL.size(); MD && i != e; i++) {
  197. Instruction *I = cast<Instruction>(VL[i]);
  198. MDNode *IMD = I->getMetadata(Kind);
  199. switch (Kind) {
  200. default:
  201. MD = nullptr; // Remove unknown metadata
  202. break;
  203. case LLVMContext::MD_tbaa:
  204. MD = MDNode::getMostGenericTBAA(MD, IMD);
  205. break;
  206. case LLVMContext::MD_alias_scope:
  207. MD = MDNode::getMostGenericAliasScope(MD, IMD);
  208. break;
  209. case LLVMContext::MD_noalias:
  210. MD = MDNode::intersect(MD, IMD);
  211. break;
  212. case LLVMContext::MD_fpmath:
  213. MD = MDNode::getMostGenericFPMath(MD, IMD);
  214. break;
  215. }
  216. }
  217. I->setMetadata(Kind, MD);
  218. }
  219. return I;
  220. }
  221. /// \returns The type that all of the values in \p VL have or null if there
  222. /// are different types.
  223. static Type* getSameType(ArrayRef<Value *> VL) {
  224. Type *Ty = VL[0]->getType();
  225. for (int i = 1, e = VL.size(); i < e; i++)
  226. if (VL[i]->getType() != Ty)
  227. return nullptr;
  228. return Ty;
  229. }
  230. /// \returns True if the ExtractElement instructions in VL can be vectorized
  231. /// to use the original vector.
  232. static bool CanReuseExtract(ArrayRef<Value *> VL) {
  233. assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
  234. // Check if all of the extracts come from the same vector and from the
  235. // correct offset.
  236. Value *VL0 = VL[0];
  237. ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
  238. Value *Vec = E0->getOperand(0);
  239. // We have to extract from the same vector type.
  240. unsigned NElts = Vec->getType()->getVectorNumElements();
  241. if (NElts != VL.size())
  242. return false;
  243. // Check that all of the indices extract from the correct offset.
  244. ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
  245. if (!CI || CI->getZExtValue())
  246. return false;
  247. for (unsigned i = 1, e = VL.size(); i < e; ++i) {
  248. ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
  249. ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
  250. if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
  251. return false;
  252. }
  253. return true;
  254. }
  255. /// \returns True if in-tree use also needs extract. This refers to
  256. /// possible scalar operand in vectorized instruction.
  257. static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
  258. TargetLibraryInfo *TLI) {
  259. unsigned Opcode = UserInst->getOpcode();
  260. switch (Opcode) {
  261. case Instruction::Load: {
  262. LoadInst *LI = cast<LoadInst>(UserInst);
  263. return (LI->getPointerOperand() == Scalar);
  264. }
  265. case Instruction::Store: {
  266. StoreInst *SI = cast<StoreInst>(UserInst);
  267. return (SI->getPointerOperand() == Scalar);
  268. }
  269. case Instruction::Call: {
  270. CallInst *CI = cast<CallInst>(UserInst);
  271. Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
  272. if (hasVectorInstrinsicScalarOpd(ID, 1)) {
  273. return (CI->getArgOperand(1) == Scalar);
  274. }
  275. }
  276. default:
  277. return false;
  278. }
  279. }
  280. /// \returns the AA location that is being access by the instruction.
  281. static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
  282. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  283. return AA->getLocation(SI);
  284. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  285. return AA->getLocation(LI);
  286. return AliasAnalysis::Location();
  287. }
  288. /// \returns True if the instruction is not a volatile or atomic load/store.
  289. static bool isSimple(Instruction *I) {
  290. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  291. return LI->isSimple();
  292. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  293. return SI->isSimple();
  294. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
  295. return !MI->isVolatile();
  296. return true;
  297. }
  298. /// Bottom Up SLP Vectorizer.
  299. class BoUpSLP {
  300. public:
  301. typedef SmallVector<Value *, 8> ValueList;
  302. typedef SmallVector<Instruction *, 16> InstrList;
  303. typedef SmallPtrSet<Value *, 16> ValueSet;
  304. typedef SmallVector<StoreInst *, 8> StoreList;
  305. BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
  306. TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
  307. LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC)
  308. : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
  309. SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
  310. Builder(Se->getContext()) {
  311. CodeMetrics::collectEphemeralValues(F, AC, EphValues);
  312. }
  313. /// \brief Vectorize the tree that starts with the elements in \p VL.
  314. /// Returns the vectorized root.
  315. Value *vectorizeTree();
  316. /// \returns the cost incurred by unwanted spills and fills, caused by
  317. /// holding live values over call sites.
  318. int getSpillCost();
  319. /// \returns the vectorization cost of the subtree that starts at \p VL.
  320. /// A negative number means that this is profitable.
  321. int getTreeCost();
  322. /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
  323. /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
  324. void buildTree(ArrayRef<Value *> Roots,
  325. ArrayRef<Value *> UserIgnoreLst = None);
  326. /// Clear the internal data structures that are created by 'buildTree'.
  327. void deleteTree() {
  328. VectorizableTree.clear();
  329. ScalarToTreeEntry.clear();
  330. MustGather.clear();
  331. ExternalUses.clear();
  332. NumLoadsWantToKeepOrder = 0;
  333. NumLoadsWantToChangeOrder = 0;
  334. for (auto &Iter : BlocksSchedules) {
  335. BlockScheduling *BS = Iter.second.get();
  336. BS->clear();
  337. }
  338. }
  339. /// \returns true if the memory operations A and B are consecutive.
  340. bool isConsecutiveAccess(Value *A, Value *B);
  341. /// \brief Perform LICM and CSE on the newly generated gather sequences.
  342. void optimizeGatherSequence();
  343. /// \returns true if it is benefitial to reverse the vector order.
  344. bool shouldReorder() const {
  345. return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
  346. }
  347. private:
  348. struct TreeEntry;
  349. /// \returns the cost of the vectorizable entry.
  350. int getEntryCost(TreeEntry *E);
  351. /// This is the recursive part of buildTree.
  352. void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
  353. /// Vectorize a single entry in the tree.
  354. Value *vectorizeTree(TreeEntry *E);
  355. /// Vectorize a single entry in the tree, starting in \p VL.
  356. Value *vectorizeTree(ArrayRef<Value *> VL);
  357. /// \returns the pointer to the vectorized value if \p VL is already
  358. /// vectorized, or NULL. They may happen in cycles.
  359. Value *alreadyVectorized(ArrayRef<Value *> VL) const;
  360. /// \brief Take the pointer operand from the Load/Store instruction.
  361. /// \returns NULL if this is not a valid Load/Store instruction.
  362. static Value *getPointerOperand(Value *I);
  363. /// \brief Take the address space operand from the Load/Store instruction.
  364. /// \returns -1 if this is not a valid Load/Store instruction.
  365. static unsigned getAddressSpaceOperand(Value *I);
  366. /// \returns the scalarization cost for this type. Scalarization in this
  367. /// context means the creation of vectors from a group of scalars.
  368. int getGatherCost(Type *Ty);
  369. /// \returns the scalarization cost for this list of values. Assuming that
  370. /// this subtree gets vectorized, we may need to extract the values from the
  371. /// roots. This method calculates the cost of extracting the values.
  372. int getGatherCost(ArrayRef<Value *> VL);
  373. /// \brief Set the Builder insert point to one after the last instruction in
  374. /// the bundle
  375. void setInsertPointAfterBundle(ArrayRef<Value *> VL);
  376. /// \returns a vector from a collection of scalars in \p VL.
  377. Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
  378. /// \returns whether the VectorizableTree is fully vectoriable and will
  379. /// be beneficial even the tree height is tiny.
  380. bool isFullyVectorizableTinyTree();
  381. /// \reorder commutative operands in alt shuffle if they result in
  382. /// vectorized code.
  383. void reorderAltShuffleOperands(ArrayRef<Value *> VL,
  384. SmallVectorImpl<Value *> &Left,
  385. SmallVectorImpl<Value *> &Right);
  386. /// \reorder commutative operands to get better probability of
  387. /// generating vectorized code.
  388. void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
  389. SmallVectorImpl<Value *> &Left,
  390. SmallVectorImpl<Value *> &Right);
  391. struct TreeEntry {
  392. TreeEntry() : Scalars(), VectorizedValue(nullptr),
  393. NeedToGather(0) {}
  394. /// \returns true if the scalars in VL are equal to this entry.
  395. bool isSame(ArrayRef<Value *> VL) const {
  396. assert(VL.size() == Scalars.size() && "Invalid size");
  397. return std::equal(VL.begin(), VL.end(), Scalars.begin());
  398. }
  399. /// A vector of scalars.
  400. ValueList Scalars;
  401. /// The Scalars are vectorized into this value. It is initialized to Null.
  402. Value *VectorizedValue;
  403. /// Do we need to gather this sequence ?
  404. bool NeedToGather;
  405. };
  406. /// Create a new VectorizableTree entry.
  407. TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
  408. VectorizableTree.push_back(TreeEntry());
  409. int idx = VectorizableTree.size() - 1;
  410. TreeEntry *Last = &VectorizableTree[idx];
  411. Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
  412. Last->NeedToGather = !Vectorized;
  413. if (Vectorized) {
  414. for (int i = 0, e = VL.size(); i != e; ++i) {
  415. assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
  416. ScalarToTreeEntry[VL[i]] = idx;
  417. }
  418. } else {
  419. MustGather.insert(VL.begin(), VL.end());
  420. }
  421. return Last;
  422. }
  423. /// -- Vectorization State --
  424. /// Holds all of the tree entries.
  425. std::vector<TreeEntry> VectorizableTree;
  426. /// Maps a specific scalar to its tree entry.
  427. SmallDenseMap<Value*, int> ScalarToTreeEntry;
  428. /// A list of scalars that we found that we need to keep as scalars.
  429. ValueSet MustGather;
  430. /// This POD struct describes one external user in the vectorized tree.
  431. struct ExternalUser {
  432. ExternalUser (Value *S, llvm::User *U, int L) :
  433. Scalar(S), User(U), Lane(L){};
  434. // Which scalar in our function.
  435. Value *Scalar;
  436. // Which user that uses the scalar.
  437. llvm::User *User;
  438. // Which lane does the scalar belong to.
  439. int Lane;
  440. };
  441. typedef SmallVector<ExternalUser, 16> UserList;
  442. /// Checks if two instructions may access the same memory.
  443. ///
  444. /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
  445. /// is invariant in the calling loop.
  446. bool isAliased(const AliasAnalysis::Location &Loc1, Instruction *Inst1,
  447. Instruction *Inst2) {
  448. // First check if the result is already in the cache.
  449. AliasCacheKey key = std::make_pair(Inst1, Inst2);
  450. Optional<bool> &result = AliasCache[key];
  451. if (result.hasValue()) {
  452. return result.getValue();
  453. }
  454. AliasAnalysis::Location Loc2 = getLocation(Inst2, AA);
  455. bool aliased = true;
  456. if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
  457. // Do the alias check.
  458. aliased = AA->alias(Loc1, Loc2);
  459. }
  460. // Store the result in the cache.
  461. result = aliased;
  462. return aliased;
  463. }
  464. typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
  465. /// Cache for alias results.
  466. /// TODO: consider moving this to the AliasAnalysis itself.
  467. DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
  468. /// Removes an instruction from its block and eventually deletes it.
  469. /// It's like Instruction::eraseFromParent() except that the actual deletion
  470. /// is delayed until BoUpSLP is destructed.
  471. /// This is required to ensure that there are no incorrect collisions in the
  472. /// AliasCache, which can happen if a new instruction is allocated at the
  473. /// same address as a previously deleted instruction.
  474. void eraseInstruction(Instruction *I) {
  475. I->removeFromParent();
  476. I->dropAllReferences();
  477. DeletedInstructions.push_back(std::unique_ptr<Instruction>(I));
  478. }
  479. /// Temporary store for deleted instructions. Instructions will be deleted
  480. /// eventually when the BoUpSLP is destructed.
  481. SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions;
  482. /// A list of values that need to extracted out of the tree.
  483. /// This list holds pairs of (Internal Scalar : External User).
  484. UserList ExternalUses;
  485. /// Values used only by @llvm.assume calls.
  486. SmallPtrSet<const Value *, 32> EphValues;
  487. /// Holds all of the instructions that we gathered.
  488. SetVector<Instruction *> GatherSeq;
  489. /// A list of blocks that we are going to CSE.
  490. SetVector<BasicBlock *> CSEBlocks;
  491. /// Contains all scheduling relevant data for an instruction.
  492. /// A ScheduleData either represents a single instruction or a member of an
  493. /// instruction bundle (= a group of instructions which is combined into a
  494. /// vector instruction).
  495. struct ScheduleData {
  496. // The initial value for the dependency counters. It means that the
  497. // dependencies are not calculated yet.
  498. enum { InvalidDeps = -1 };
  499. ScheduleData()
  500. : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
  501. NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
  502. Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
  503. UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
  504. void init(int BlockSchedulingRegionID) {
  505. FirstInBundle = this;
  506. NextInBundle = nullptr;
  507. NextLoadStore = nullptr;
  508. IsScheduled = false;
  509. SchedulingRegionID = BlockSchedulingRegionID;
  510. UnscheduledDepsInBundle = UnscheduledDeps;
  511. clearDependencies();
  512. }
  513. /// Returns true if the dependency information has been calculated.
  514. bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
  515. /// Returns true for single instructions and for bundle representatives
  516. /// (= the head of a bundle).
  517. bool isSchedulingEntity() const { return FirstInBundle == this; }
  518. /// Returns true if it represents an instruction bundle and not only a
  519. /// single instruction.
  520. bool isPartOfBundle() const {
  521. return NextInBundle != nullptr || FirstInBundle != this;
  522. }
  523. /// Returns true if it is ready for scheduling, i.e. it has no more
  524. /// unscheduled depending instructions/bundles.
  525. bool isReady() const {
  526. assert(isSchedulingEntity() &&
  527. "can't consider non-scheduling entity for ready list");
  528. return UnscheduledDepsInBundle == 0 && !IsScheduled;
  529. }
  530. /// Modifies the number of unscheduled dependencies, also updating it for
  531. /// the whole bundle.
  532. int incrementUnscheduledDeps(int Incr) {
  533. UnscheduledDeps += Incr;
  534. return FirstInBundle->UnscheduledDepsInBundle += Incr;
  535. }
  536. /// Sets the number of unscheduled dependencies to the number of
  537. /// dependencies.
  538. void resetUnscheduledDeps() {
  539. incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
  540. }
  541. /// Clears all dependency information.
  542. void clearDependencies() {
  543. Dependencies = InvalidDeps;
  544. resetUnscheduledDeps();
  545. MemoryDependencies.clear();
  546. }
  547. void dump(raw_ostream &os) const {
  548. if (!isSchedulingEntity()) {
  549. os << "/ " << *Inst;
  550. } else if (NextInBundle) {
  551. os << '[' << *Inst;
  552. ScheduleData *SD = NextInBundle;
  553. while (SD) {
  554. os << ';' << *SD->Inst;
  555. SD = SD->NextInBundle;
  556. }
  557. os << ']';
  558. } else {
  559. os << *Inst;
  560. }
  561. }
  562. Instruction *Inst;
  563. /// Points to the head in an instruction bundle (and always to this for
  564. /// single instructions).
  565. ScheduleData *FirstInBundle;
  566. /// Single linked list of all instructions in a bundle. Null if it is a
  567. /// single instruction.
  568. ScheduleData *NextInBundle;
  569. /// Single linked list of all memory instructions (e.g. load, store, call)
  570. /// in the block - until the end of the scheduling region.
  571. ScheduleData *NextLoadStore;
  572. /// The dependent memory instructions.
  573. /// This list is derived on demand in calculateDependencies().
  574. SmallVector<ScheduleData *, 4> MemoryDependencies;
  575. /// This ScheduleData is in the current scheduling region if this matches
  576. /// the current SchedulingRegionID of BlockScheduling.
  577. int SchedulingRegionID;
  578. /// Used for getting a "good" final ordering of instructions.
  579. int SchedulingPriority;
  580. /// The number of dependencies. Constitutes of the number of users of the
  581. /// instruction plus the number of dependent memory instructions (if any).
  582. /// This value is calculated on demand.
  583. /// If InvalidDeps, the number of dependencies is not calculated yet.
  584. ///
  585. int Dependencies;
  586. /// The number of dependencies minus the number of dependencies of scheduled
  587. /// instructions. As soon as this is zero, the instruction/bundle gets ready
  588. /// for scheduling.
  589. /// Note that this is negative as long as Dependencies is not calculated.
  590. int UnscheduledDeps;
  591. /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
  592. /// single instructions.
  593. int UnscheduledDepsInBundle;
  594. /// True if this instruction is scheduled (or considered as scheduled in the
  595. /// dry-run).
  596. bool IsScheduled;
  597. };
  598. #ifndef NDEBUG
  599. friend raw_ostream &operator<<(raw_ostream &os,
  600. const BoUpSLP::ScheduleData &SD);
  601. #endif
  602. /// Contains all scheduling data for a basic block.
  603. ///
  604. struct BlockScheduling {
  605. BlockScheduling(BasicBlock *BB)
  606. : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
  607. ScheduleStart(nullptr), ScheduleEnd(nullptr),
  608. FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
  609. // Make sure that the initial SchedulingRegionID is greater than the
  610. // initial SchedulingRegionID in ScheduleData (which is 0).
  611. SchedulingRegionID(1) {}
  612. void clear() {
  613. ReadyInsts.clear();
  614. ScheduleStart = nullptr;
  615. ScheduleEnd = nullptr;
  616. FirstLoadStoreInRegion = nullptr;
  617. LastLoadStoreInRegion = nullptr;
  618. // Make a new scheduling region, i.e. all existing ScheduleData is not
  619. // in the new region yet.
  620. ++SchedulingRegionID;
  621. }
  622. ScheduleData *getScheduleData(Value *V) {
  623. ScheduleData *SD = ScheduleDataMap[V];
  624. if (SD && SD->SchedulingRegionID == SchedulingRegionID)
  625. return SD;
  626. return nullptr;
  627. }
  628. bool isInSchedulingRegion(ScheduleData *SD) {
  629. return SD->SchedulingRegionID == SchedulingRegionID;
  630. }
  631. /// Marks an instruction as scheduled and puts all dependent ready
  632. /// instructions into the ready-list.
  633. template <typename ReadyListType>
  634. void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
  635. SD->IsScheduled = true;
  636. DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
  637. ScheduleData *BundleMember = SD;
  638. while (BundleMember) {
  639. // Handle the def-use chain dependencies.
  640. for (Use &U : BundleMember->Inst->operands()) {
  641. ScheduleData *OpDef = getScheduleData(U.get());
  642. if (OpDef && OpDef->hasValidDependencies() &&
  643. OpDef->incrementUnscheduledDeps(-1) == 0) {
  644. // There are no more unscheduled dependencies after decrementing,
  645. // so we can put the dependent instruction into the ready list.
  646. ScheduleData *DepBundle = OpDef->FirstInBundle;
  647. assert(!DepBundle->IsScheduled &&
  648. "already scheduled bundle gets ready");
  649. ReadyList.insert(DepBundle);
  650. DEBUG(dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n");
  651. }
  652. }
  653. // Handle the memory dependencies.
  654. for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
  655. if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
  656. // There are no more unscheduled dependencies after decrementing,
  657. // so we can put the dependent instruction into the ready list.
  658. ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
  659. assert(!DepBundle->IsScheduled &&
  660. "already scheduled bundle gets ready");
  661. ReadyList.insert(DepBundle);
  662. DEBUG(dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n");
  663. }
  664. }
  665. BundleMember = BundleMember->NextInBundle;
  666. }
  667. }
  668. /// Put all instructions into the ReadyList which are ready for scheduling.
  669. template <typename ReadyListType>
  670. void initialFillReadyList(ReadyListType &ReadyList) {
  671. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  672. ScheduleData *SD = getScheduleData(I);
  673. if (SD->isSchedulingEntity() && SD->isReady()) {
  674. ReadyList.insert(SD);
  675. DEBUG(dbgs() << "SLP: initially in ready list: " << *I << "\n");
  676. }
  677. }
  678. }
  679. /// Checks if a bundle of instructions can be scheduled, i.e. has no
  680. /// cyclic dependencies. This is only a dry-run, no instructions are
  681. /// actually moved at this stage.
  682. bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
  683. /// Un-bundles a group of instructions.
  684. void cancelScheduling(ArrayRef<Value *> VL);
  685. /// Extends the scheduling region so that V is inside the region.
  686. void extendSchedulingRegion(Value *V);
  687. /// Initialize the ScheduleData structures for new instructions in the
  688. /// scheduling region.
  689. void initScheduleData(Instruction *FromI, Instruction *ToI,
  690. ScheduleData *PrevLoadStore,
  691. ScheduleData *NextLoadStore);
  692. /// Updates the dependency information of a bundle and of all instructions/
  693. /// bundles which depend on the original bundle.
  694. void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
  695. BoUpSLP *SLP);
  696. /// Sets all instruction in the scheduling region to un-scheduled.
  697. void resetSchedule();
  698. BasicBlock *BB;
  699. /// Simple memory allocation for ScheduleData.
  700. std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
  701. /// The size of a ScheduleData array in ScheduleDataChunks.
  702. int ChunkSize;
  703. /// The allocator position in the current chunk, which is the last entry
  704. /// of ScheduleDataChunks.
  705. int ChunkPos;
  706. /// Attaches ScheduleData to Instruction.
  707. /// Note that the mapping survives during all vectorization iterations, i.e.
  708. /// ScheduleData structures are recycled.
  709. DenseMap<Value *, ScheduleData *> ScheduleDataMap;
  710. struct ReadyList : SmallVector<ScheduleData *, 8> {
  711. void insert(ScheduleData *SD) { push_back(SD); }
  712. };
  713. /// The ready-list for scheduling (only used for the dry-run).
  714. ReadyList ReadyInsts;
  715. /// The first instruction of the scheduling region.
  716. Instruction *ScheduleStart;
  717. /// The first instruction _after_ the scheduling region.
  718. Instruction *ScheduleEnd;
  719. /// The first memory accessing instruction in the scheduling region
  720. /// (can be null).
  721. ScheduleData *FirstLoadStoreInRegion;
  722. /// The last memory accessing instruction in the scheduling region
  723. /// (can be null).
  724. ScheduleData *LastLoadStoreInRegion;
  725. /// The ID of the scheduling region. For a new vectorization iteration this
  726. /// is incremented which "removes" all ScheduleData from the region.
  727. int SchedulingRegionID;
  728. };
  729. /// Attaches the BlockScheduling structures to basic blocks.
  730. MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
  731. /// Performs the "real" scheduling. Done before vectorization is actually
  732. /// performed in a basic block.
  733. void scheduleBlock(BlockScheduling *BS);
  734. /// List of users to ignore during scheduling and that don't need extracting.
  735. ArrayRef<Value *> UserIgnoreList;
  736. // Number of load-bundles, which contain consecutive loads.
  737. int NumLoadsWantToKeepOrder;
  738. // Number of load-bundles of size 2, which are consecutive loads if reversed.
  739. int NumLoadsWantToChangeOrder;
  740. // Analysis and block reference.
  741. Function *F;
  742. ScalarEvolution *SE;
  743. const DataLayout *DL;
  744. TargetTransformInfo *TTI;
  745. TargetLibraryInfo *TLI;
  746. AliasAnalysis *AA;
  747. LoopInfo *LI;
  748. DominatorTree *DT;
  749. /// Instruction builder to construct the vectorized tree.
  750. IRBuilder<> Builder;
  751. };
  752. #ifndef NDEBUG
  753. raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
  754. SD.dump(os);
  755. return os;
  756. }
  757. #endif
  758. void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
  759. ArrayRef<Value *> UserIgnoreLst) {
  760. deleteTree();
  761. UserIgnoreList = UserIgnoreLst;
  762. if (!getSameType(Roots))
  763. return;
  764. buildTree_rec(Roots, 0);
  765. // Collect the values that we need to extract from the tree.
  766. for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
  767. TreeEntry *Entry = &VectorizableTree[EIdx];
  768. // For each lane:
  769. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  770. Value *Scalar = Entry->Scalars[Lane];
  771. // No need to handle users of gathered values.
  772. if (Entry->NeedToGather)
  773. continue;
  774. for (User *U : Scalar->users()) {
  775. DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
  776. Instruction *UserInst = dyn_cast<Instruction>(U);
  777. if (!UserInst)
  778. continue;
  779. // Skip in-tree scalars that become vectors
  780. if (ScalarToTreeEntry.count(U)) {
  781. int Idx = ScalarToTreeEntry[U];
  782. TreeEntry *UseEntry = &VectorizableTree[Idx];
  783. Value *UseScalar = UseEntry->Scalars[0];
  784. // Some in-tree scalars will remain as scalar in vectorized
  785. // instructions. If that is the case, the one in Lane 0 will
  786. // be used.
  787. if (UseScalar != U ||
  788. !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
  789. DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
  790. << ".\n");
  791. assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
  792. continue;
  793. }
  794. }
  795. // Ignore users in the user ignore list.
  796. if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
  797. UserIgnoreList.end())
  798. continue;
  799. DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
  800. Lane << " from " << *Scalar << ".\n");
  801. ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
  802. }
  803. }
  804. }
  805. }
  806. void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
  807. bool SameTy = getSameType(VL); (void)SameTy;
  808. bool isAltShuffle = false;
  809. assert(SameTy && "Invalid types!");
  810. if (Depth == RecursionMaxDepth) {
  811. DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
  812. newTreeEntry(VL, false);
  813. return;
  814. }
  815. // Don't handle vectors.
  816. if (VL[0]->getType()->isVectorTy()) {
  817. DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
  818. newTreeEntry(VL, false);
  819. return;
  820. }
  821. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  822. if (SI->getValueOperand()->getType()->isVectorTy()) {
  823. DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
  824. newTreeEntry(VL, false);
  825. return;
  826. }
  827. unsigned Opcode = getSameOpcode(VL);
  828. // Check that this shuffle vector refers to the alternate
  829. // sequence of opcodes.
  830. if (Opcode == Instruction::ShuffleVector) {
  831. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  832. unsigned Op = I0->getOpcode();
  833. if (Op != Instruction::ShuffleVector)
  834. isAltShuffle = true;
  835. }
  836. // If all of the operands are identical or constant we have a simple solution.
  837. if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
  838. DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
  839. newTreeEntry(VL, false);
  840. return;
  841. }
  842. // We now know that this is a vector of instructions of the same type from
  843. // the same block.
  844. // Don't vectorize ephemeral values.
  845. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  846. if (EphValues.count(VL[i])) {
  847. DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
  848. ") is ephemeral.\n");
  849. newTreeEntry(VL, false);
  850. return;
  851. }
  852. }
  853. // Check if this is a duplicate of another entry.
  854. if (ScalarToTreeEntry.count(VL[0])) {
  855. int Idx = ScalarToTreeEntry[VL[0]];
  856. TreeEntry *E = &VectorizableTree[Idx];
  857. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  858. DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
  859. if (E->Scalars[i] != VL[i]) {
  860. DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
  861. newTreeEntry(VL, false);
  862. return;
  863. }
  864. }
  865. DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
  866. return;
  867. }
  868. // Check that none of the instructions in the bundle are already in the tree.
  869. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  870. if (ScalarToTreeEntry.count(VL[i])) {
  871. DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
  872. ") is already in tree.\n");
  873. newTreeEntry(VL, false);
  874. return;
  875. }
  876. }
  877. // If any of the scalars is marked as a value that needs to stay scalar then
  878. // we need to gather the scalars.
  879. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  880. if (MustGather.count(VL[i])) {
  881. DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
  882. newTreeEntry(VL, false);
  883. return;
  884. }
  885. }
  886. // Check that all of the users of the scalars that we want to vectorize are
  887. // schedulable.
  888. Instruction *VL0 = cast<Instruction>(VL[0]);
  889. BasicBlock *BB = cast<Instruction>(VL0)->getParent();
  890. if (!DT->isReachableFromEntry(BB)) {
  891. // Don't go into unreachable blocks. They may contain instructions with
  892. // dependency cycles which confuse the final scheduling.
  893. DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
  894. newTreeEntry(VL, false);
  895. return;
  896. }
  897. // Check that every instructions appears once in this bundle.
  898. for (unsigned i = 0, e = VL.size(); i < e; ++i)
  899. for (unsigned j = i+1; j < e; ++j)
  900. if (VL[i] == VL[j]) {
  901. DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
  902. newTreeEntry(VL, false);
  903. return;
  904. }
  905. auto &BSRef = BlocksSchedules[BB];
  906. if (!BSRef) {
  907. BSRef = llvm::make_unique<BlockScheduling>(BB);
  908. }
  909. BlockScheduling &BS = *BSRef.get();
  910. if (!BS.tryScheduleBundle(VL, this)) {
  911. DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
  912. BS.cancelScheduling(VL);
  913. newTreeEntry(VL, false);
  914. return;
  915. }
  916. DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
  917. switch (Opcode) {
  918. case Instruction::PHI: {
  919. PHINode *PH = dyn_cast<PHINode>(VL0);
  920. // Check for terminator values (e.g. invoke).
  921. for (unsigned j = 0; j < VL.size(); ++j)
  922. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  923. TerminatorInst *Term = dyn_cast<TerminatorInst>(
  924. cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
  925. if (Term) {
  926. DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
  927. BS.cancelScheduling(VL);
  928. newTreeEntry(VL, false);
  929. return;
  930. }
  931. }
  932. newTreeEntry(VL, true);
  933. DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
  934. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  935. ValueList Operands;
  936. // Prepare the operand vector.
  937. for (unsigned j = 0; j < VL.size(); ++j)
  938. Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
  939. PH->getIncomingBlock(i)));
  940. buildTree_rec(Operands, Depth + 1);
  941. }
  942. return;
  943. }
  944. case Instruction::ExtractElement: {
  945. bool Reuse = CanReuseExtract(VL);
  946. if (Reuse) {
  947. DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
  948. } else {
  949. BS.cancelScheduling(VL);
  950. }
  951. newTreeEntry(VL, Reuse);
  952. return;
  953. }
  954. case Instruction::Load: {
  955. // Check if the loads are consecutive or of we need to swizzle them.
  956. for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
  957. LoadInst *L = cast<LoadInst>(VL[i]);
  958. if (!L->isSimple()) {
  959. BS.cancelScheduling(VL);
  960. newTreeEntry(VL, false);
  961. DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
  962. return;
  963. }
  964. if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
  965. if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
  966. ++NumLoadsWantToChangeOrder;
  967. }
  968. BS.cancelScheduling(VL);
  969. newTreeEntry(VL, false);
  970. DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
  971. return;
  972. }
  973. }
  974. ++NumLoadsWantToKeepOrder;
  975. newTreeEntry(VL, true);
  976. DEBUG(dbgs() << "SLP: added a vector of loads.\n");
  977. return;
  978. }
  979. case Instruction::ZExt:
  980. case Instruction::SExt:
  981. case Instruction::FPToUI:
  982. case Instruction::FPToSI:
  983. case Instruction::FPExt:
  984. case Instruction::PtrToInt:
  985. case Instruction::IntToPtr:
  986. case Instruction::SIToFP:
  987. case Instruction::UIToFP:
  988. case Instruction::Trunc:
  989. case Instruction::FPTrunc:
  990. case Instruction::BitCast: {
  991. Type *SrcTy = VL0->getOperand(0)->getType();
  992. for (unsigned i = 0; i < VL.size(); ++i) {
  993. Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
  994. if (Ty != SrcTy || !isValidElementType(Ty)) {
  995. BS.cancelScheduling(VL);
  996. newTreeEntry(VL, false);
  997. DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
  998. return;
  999. }
  1000. }
  1001. newTreeEntry(VL, true);
  1002. DEBUG(dbgs() << "SLP: added a vector of casts.\n");
  1003. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  1004. ValueList Operands;
  1005. // Prepare the operand vector.
  1006. for (unsigned j = 0; j < VL.size(); ++j)
  1007. Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
  1008. buildTree_rec(Operands, Depth+1);
  1009. }
  1010. return;
  1011. }
  1012. case Instruction::ICmp:
  1013. case Instruction::FCmp: {
  1014. // Check that all of the compares have the same predicate.
  1015. CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
  1016. Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
  1017. for (unsigned i = 1, e = VL.size(); i < e; ++i) {
  1018. CmpInst *Cmp = cast<CmpInst>(VL[i]);
  1019. if (Cmp->getPredicate() != P0 ||
  1020. Cmp->getOperand(0)->getType() != ComparedTy) {
  1021. BS.cancelScheduling(VL);
  1022. newTreeEntry(VL, false);
  1023. DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
  1024. return;
  1025. }
  1026. }
  1027. newTreeEntry(VL, true);
  1028. DEBUG(dbgs() << "SLP: added a vector of compares.\n");
  1029. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  1030. ValueList Operands;
  1031. // Prepare the operand vector.
  1032. for (unsigned j = 0; j < VL.size(); ++j)
  1033. Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
  1034. buildTree_rec(Operands, Depth+1);
  1035. }
  1036. return;
  1037. }
  1038. case Instruction::Select:
  1039. case Instruction::Add:
  1040. case Instruction::FAdd:
  1041. case Instruction::Sub:
  1042. case Instruction::FSub:
  1043. case Instruction::Mul:
  1044. case Instruction::FMul:
  1045. case Instruction::UDiv:
  1046. case Instruction::SDiv:
  1047. case Instruction::FDiv:
  1048. case Instruction::URem:
  1049. case Instruction::SRem:
  1050. case Instruction::FRem:
  1051. case Instruction::Shl:
  1052. case Instruction::LShr:
  1053. case Instruction::AShr:
  1054. case Instruction::And:
  1055. case Instruction::Or:
  1056. case Instruction::Xor: {
  1057. newTreeEntry(VL, true);
  1058. DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
  1059. // Sort operands of the instructions so that each side is more likely to
  1060. // have the same opcode.
  1061. if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
  1062. ValueList Left, Right;
  1063. reorderInputsAccordingToOpcode(VL, Left, Right);
  1064. buildTree_rec(Left, Depth + 1);
  1065. buildTree_rec(Right, Depth + 1);
  1066. return;
  1067. }
  1068. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  1069. ValueList Operands;
  1070. // Prepare the operand vector.
  1071. for (unsigned j = 0; j < VL.size(); ++j)
  1072. Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
  1073. buildTree_rec(Operands, Depth+1);
  1074. }
  1075. return;
  1076. }
  1077. case Instruction::GetElementPtr: {
  1078. // We don't combine GEPs with complicated (nested) indexing.
  1079. for (unsigned j = 0; j < VL.size(); ++j) {
  1080. if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
  1081. DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
  1082. BS.cancelScheduling(VL);
  1083. newTreeEntry(VL, false);
  1084. return;
  1085. }
  1086. }
  1087. // We can't combine several GEPs into one vector if they operate on
  1088. // different types.
  1089. Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
  1090. for (unsigned j = 0; j < VL.size(); ++j) {
  1091. Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
  1092. if (Ty0 != CurTy) {
  1093. DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
  1094. BS.cancelScheduling(VL);
  1095. newTreeEntry(VL, false);
  1096. return;
  1097. }
  1098. }
  1099. // We don't combine GEPs with non-constant indexes.
  1100. for (unsigned j = 0; j < VL.size(); ++j) {
  1101. auto Op = cast<Instruction>(VL[j])->getOperand(1);
  1102. if (!isa<ConstantInt>(Op)) {
  1103. DEBUG(
  1104. dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
  1105. BS.cancelScheduling(VL);
  1106. newTreeEntry(VL, false);
  1107. return;
  1108. }
  1109. }
  1110. newTreeEntry(VL, true);
  1111. DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
  1112. for (unsigned i = 0, e = 2; i < e; ++i) {
  1113. ValueList Operands;
  1114. // Prepare the operand vector.
  1115. for (unsigned j = 0; j < VL.size(); ++j)
  1116. Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
  1117. buildTree_rec(Operands, Depth + 1);
  1118. }
  1119. return;
  1120. }
  1121. case Instruction::Store: {
  1122. // Check if the stores are consecutive or of we need to swizzle them.
  1123. for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
  1124. if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
  1125. BS.cancelScheduling(VL);
  1126. newTreeEntry(VL, false);
  1127. DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
  1128. return;
  1129. }
  1130. newTreeEntry(VL, true);
  1131. DEBUG(dbgs() << "SLP: added a vector of stores.\n");
  1132. ValueList Operands;
  1133. for (unsigned j = 0; j < VL.size(); ++j)
  1134. Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
  1135. buildTree_rec(Operands, Depth + 1);
  1136. return;
  1137. }
  1138. case Instruction::Call: {
  1139. // Check if the calls are all to the same vectorizable intrinsic.
  1140. CallInst *CI = cast<CallInst>(VL[0]);
  1141. // Check if this is an Intrinsic call or something that can be
  1142. // represented by an intrinsic call
  1143. Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
  1144. if (!isTriviallyVectorizable(ID)) {
  1145. BS.cancelScheduling(VL);
  1146. newTreeEntry(VL, false);
  1147. DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
  1148. return;
  1149. }
  1150. Function *Int = CI->getCalledFunction();
  1151. Value *A1I = nullptr;
  1152. if (hasVectorInstrinsicScalarOpd(ID, 1))
  1153. A1I = CI->getArgOperand(1);
  1154. for (unsigned i = 1, e = VL.size(); i != e; ++i) {
  1155. CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
  1156. if (!CI2 || CI2->getCalledFunction() != Int ||
  1157. getIntrinsicIDForCall(CI2, TLI) != ID) {
  1158. BS.cancelScheduling(VL);
  1159. newTreeEntry(VL, false);
  1160. DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
  1161. << "\n");
  1162. return;
  1163. }
  1164. // ctlz,cttz and powi are special intrinsics whose second argument
  1165. // should be same in order for them to be vectorized.
  1166. if (hasVectorInstrinsicScalarOpd(ID, 1)) {
  1167. Value *A1J = CI2->getArgOperand(1);
  1168. if (A1I != A1J) {
  1169. BS.cancelScheduling(VL);
  1170. newTreeEntry(VL, false);
  1171. DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
  1172. << " argument "<< A1I<<"!=" << A1J
  1173. << "\n");
  1174. return;
  1175. }
  1176. }
  1177. }
  1178. newTreeEntry(VL, true);
  1179. for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
  1180. ValueList Operands;
  1181. // Prepare the operand vector.
  1182. for (unsigned j = 0; j < VL.size(); ++j) {
  1183. CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
  1184. Operands.push_back(CI2->getArgOperand(i));
  1185. }
  1186. buildTree_rec(Operands, Depth + 1);
  1187. }
  1188. return;
  1189. }
  1190. case Instruction::ShuffleVector: {
  1191. // If this is not an alternate sequence of opcode like add-sub
  1192. // then do not vectorize this instruction.
  1193. if (!isAltShuffle) {
  1194. BS.cancelScheduling(VL);
  1195. newTreeEntry(VL, false);
  1196. DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
  1197. return;
  1198. }
  1199. newTreeEntry(VL, true);
  1200. DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
  1201. // Reorder operands if reordering would enable vectorization.
  1202. if (isa<BinaryOperator>(VL0)) {
  1203. ValueList Left, Right;
  1204. reorderAltShuffleOperands(VL, Left, Right);
  1205. buildTree_rec(Left, Depth + 1);
  1206. buildTree_rec(Right, Depth + 1);
  1207. return;
  1208. }
  1209. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  1210. ValueList Operands;
  1211. // Prepare the operand vector.
  1212. for (unsigned j = 0; j < VL.size(); ++j)
  1213. Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
  1214. buildTree_rec(Operands, Depth + 1);
  1215. }
  1216. return;
  1217. }
  1218. default:
  1219. BS.cancelScheduling(VL);
  1220. newTreeEntry(VL, false);
  1221. DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
  1222. return;
  1223. }
  1224. }
  1225. int BoUpSLP::getEntryCost(TreeEntry *E) {
  1226. ArrayRef<Value*> VL = E->Scalars;
  1227. Type *ScalarTy = VL[0]->getType();
  1228. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  1229. ScalarTy = SI->getValueOperand()->getType();
  1230. VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
  1231. if (E->NeedToGather) {
  1232. if (allConstant(VL))
  1233. return 0;
  1234. if (isSplat(VL)) {
  1235. return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
  1236. }
  1237. return getGatherCost(E->Scalars);
  1238. }
  1239. unsigned Opcode = getSameOpcode(VL);
  1240. assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
  1241. Instruction *VL0 = cast<Instruction>(VL[0]);
  1242. switch (Opcode) {
  1243. case Instruction::PHI: {
  1244. return 0;
  1245. }
  1246. case Instruction::ExtractElement: {
  1247. if (CanReuseExtract(VL)) {
  1248. int DeadCost = 0;
  1249. for (unsigned i = 0, e = VL.size(); i < e; ++i) {
  1250. ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
  1251. if (E->hasOneUse())
  1252. // Take credit for instruction that will become dead.
  1253. DeadCost +=
  1254. TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
  1255. }
  1256. return -DeadCost;
  1257. }
  1258. return getGatherCost(VecTy);
  1259. }
  1260. case Instruction::ZExt:
  1261. case Instruction::SExt:
  1262. case Instruction::FPToUI:
  1263. case Instruction::FPToSI:
  1264. case Instruction::FPExt:
  1265. case Instruction::PtrToInt:
  1266. case Instruction::IntToPtr:
  1267. case Instruction::SIToFP:
  1268. case Instruction::UIToFP:
  1269. case Instruction::Trunc:
  1270. case Instruction::FPTrunc:
  1271. case Instruction::BitCast: {
  1272. Type *SrcTy = VL0->getOperand(0)->getType();
  1273. // Calculate the cost of this instruction.
  1274. int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
  1275. VL0->getType(), SrcTy);
  1276. VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
  1277. int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
  1278. return VecCost - ScalarCost;
  1279. }
  1280. case Instruction::FCmp:
  1281. case Instruction::ICmp:
  1282. case Instruction::Select:
  1283. case Instruction::Add:
  1284. case Instruction::FAdd:
  1285. case Instruction::Sub:
  1286. case Instruction::FSub:
  1287. case Instruction::Mul:
  1288. case Instruction::FMul:
  1289. case Instruction::UDiv:
  1290. case Instruction::SDiv:
  1291. case Instruction::FDiv:
  1292. case Instruction::URem:
  1293. case Instruction::SRem:
  1294. case Instruction::FRem:
  1295. case Instruction::Shl:
  1296. case Instruction::LShr:
  1297. case Instruction::AShr:
  1298. case Instruction::And:
  1299. case Instruction::Or:
  1300. case Instruction::Xor: {
  1301. // Calculate the cost of this instruction.
  1302. int ScalarCost = 0;
  1303. int VecCost = 0;
  1304. if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
  1305. Opcode == Instruction::Select) {
  1306. VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
  1307. ScalarCost = VecTy->getNumElements() *
  1308. TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
  1309. VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
  1310. } else {
  1311. // Certain instructions can be cheaper to vectorize if they have a
  1312. // constant second vector operand.
  1313. TargetTransformInfo::OperandValueKind Op1VK =
  1314. TargetTransformInfo::OK_AnyValue;
  1315. TargetTransformInfo::OperandValueKind Op2VK =
  1316. TargetTransformInfo::OK_UniformConstantValue;
  1317. TargetTransformInfo::OperandValueProperties Op1VP =
  1318. TargetTransformInfo::OP_None;
  1319. TargetTransformInfo::OperandValueProperties Op2VP =
  1320. TargetTransformInfo::OP_None;
  1321. // If all operands are exactly the same ConstantInt then set the
  1322. // operand kind to OK_UniformConstantValue.
  1323. // If instead not all operands are constants, then set the operand kind
  1324. // to OK_AnyValue. If all operands are constants but not the same,
  1325. // then set the operand kind to OK_NonUniformConstantValue.
  1326. ConstantInt *CInt = nullptr;
  1327. for (unsigned i = 0; i < VL.size(); ++i) {
  1328. const Instruction *I = cast<Instruction>(VL[i]);
  1329. if (!isa<ConstantInt>(I->getOperand(1))) {
  1330. Op2VK = TargetTransformInfo::OK_AnyValue;
  1331. break;
  1332. }
  1333. if (i == 0) {
  1334. CInt = cast<ConstantInt>(I->getOperand(1));
  1335. continue;
  1336. }
  1337. if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
  1338. CInt != cast<ConstantInt>(I->getOperand(1)))
  1339. Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
  1340. }
  1341. // FIXME: Currently cost of model modification for division by
  1342. // power of 2 is handled only for X86. Add support for other targets.
  1343. if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
  1344. CInt->getValue().isPowerOf2())
  1345. Op2VP = TargetTransformInfo::OP_PowerOf2;
  1346. ScalarCost = VecTy->getNumElements() *
  1347. TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
  1348. Op1VP, Op2VP);
  1349. VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
  1350. Op1VP, Op2VP);
  1351. }
  1352. return VecCost - ScalarCost;
  1353. }
  1354. case Instruction::GetElementPtr: {
  1355. TargetTransformInfo::OperandValueKind Op1VK =
  1356. TargetTransformInfo::OK_AnyValue;
  1357. TargetTransformInfo::OperandValueKind Op2VK =
  1358. TargetTransformInfo::OK_UniformConstantValue;
  1359. int ScalarCost =
  1360. VecTy->getNumElements() *
  1361. TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
  1362. int VecCost =
  1363. TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
  1364. return VecCost - ScalarCost;
  1365. }
  1366. case Instruction::Load: {
  1367. // Cost of wide load - cost of scalar loads.
  1368. int ScalarLdCost = VecTy->getNumElements() *
  1369. TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
  1370. int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
  1371. return VecLdCost - ScalarLdCost;
  1372. }
  1373. case Instruction::Store: {
  1374. // We know that we can merge the stores. Calculate the cost.
  1375. int ScalarStCost = VecTy->getNumElements() *
  1376. TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
  1377. int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
  1378. return VecStCost - ScalarStCost;
  1379. }
  1380. case Instruction::Call: {
  1381. CallInst *CI = cast<CallInst>(VL0);
  1382. Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
  1383. // Calculate the cost of the scalar and vector calls.
  1384. SmallVector<Type*, 4> ScalarTys, VecTys;
  1385. for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
  1386. ScalarTys.push_back(CI->getArgOperand(op)->getType());
  1387. VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
  1388. VecTy->getNumElements()));
  1389. }
  1390. int ScalarCallCost = VecTy->getNumElements() *
  1391. TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
  1392. int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
  1393. DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
  1394. << " (" << VecCallCost << "-" << ScalarCallCost << ")"
  1395. << " for " << *CI << "\n");
  1396. return VecCallCost - ScalarCallCost;
  1397. }
  1398. case Instruction::ShuffleVector: {
  1399. TargetTransformInfo::OperandValueKind Op1VK =
  1400. TargetTransformInfo::OK_AnyValue;
  1401. TargetTransformInfo::OperandValueKind Op2VK =
  1402. TargetTransformInfo::OK_AnyValue;
  1403. int ScalarCost = 0;
  1404. int VecCost = 0;
  1405. for (unsigned i = 0; i < VL.size(); ++i) {
  1406. Instruction *I = cast<Instruction>(VL[i]);
  1407. if (!I)
  1408. break;
  1409. ScalarCost +=
  1410. TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
  1411. }
  1412. // VecCost is equal to sum of the cost of creating 2 vectors
  1413. // and the cost of creating shuffle.
  1414. Instruction *I0 = cast<Instruction>(VL[0]);
  1415. VecCost =
  1416. TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
  1417. Instruction *I1 = cast<Instruction>(VL[1]);
  1418. VecCost +=
  1419. TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
  1420. VecCost +=
  1421. TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
  1422. return VecCost - ScalarCost;
  1423. }
  1424. default:
  1425. llvm_unreachable("Unknown instruction");
  1426. }
  1427. }
  1428. bool BoUpSLP::isFullyVectorizableTinyTree() {
  1429. DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
  1430. VectorizableTree.size() << " is fully vectorizable .\n");
  1431. // We only handle trees of height 2.
  1432. if (VectorizableTree.size() != 2)
  1433. return false;
  1434. // Handle splat stores.
  1435. if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
  1436. return true;
  1437. // Gathering cost would be too much for tiny trees.
  1438. if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
  1439. return false;
  1440. return true;
  1441. }
  1442. int BoUpSLP::getSpillCost() {
  1443. // Walk from the bottom of the tree to the top, tracking which values are
  1444. // live. When we see a call instruction that is not part of our tree,
  1445. // query TTI to see if there is a cost to keeping values live over it
  1446. // (for example, if spills and fills are required).
  1447. unsigned BundleWidth = VectorizableTree.front().Scalars.size();
  1448. int Cost = 0;
  1449. SmallPtrSet<Instruction*, 4> LiveValues;
  1450. Instruction *PrevInst = nullptr;
  1451. for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
  1452. Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
  1453. if (!Inst)
  1454. continue;
  1455. if (!PrevInst) {
  1456. PrevInst = Inst;
  1457. continue;
  1458. }
  1459. DEBUG(
  1460. dbgs() << "SLP: #LV: " << LiveValues.size();
  1461. for (auto *X : LiveValues)
  1462. dbgs() << " " << X->getName();
  1463. dbgs() << ", Looking at ";
  1464. Inst->dump();
  1465. );
  1466. // Update LiveValues.
  1467. LiveValues.erase(PrevInst);
  1468. for (auto &J : PrevInst->operands()) {
  1469. if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
  1470. LiveValues.insert(cast<Instruction>(&*J));
  1471. }
  1472. // Now find the sequence of instructions between PrevInst and Inst.
  1473. BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
  1474. --PrevInstIt;
  1475. while (InstIt != PrevInstIt) {
  1476. if (PrevInstIt == PrevInst->getParent()->rend()) {
  1477. PrevInstIt = Inst->getParent()->rbegin();
  1478. continue;
  1479. }
  1480. if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
  1481. SmallVector<Type*, 4> V;
  1482. for (auto *II : LiveValues)
  1483. V.push_back(VectorType::get(II->getType(), BundleWidth));
  1484. Cost += TTI->getCostOfKeepingLiveOverCall(V);
  1485. }
  1486. ++PrevInstIt;
  1487. }
  1488. PrevInst = Inst;
  1489. }
  1490. DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
  1491. return Cost;
  1492. }
  1493. int BoUpSLP::getTreeCost() {
  1494. int Cost = 0;
  1495. DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
  1496. VectorizableTree.size() << ".\n");
  1497. // We only vectorize tiny trees if it is fully vectorizable.
  1498. if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
  1499. if (VectorizableTree.empty()) {
  1500. assert(!ExternalUses.size() && "We should not have any external users");
  1501. }
  1502. return INT_MAX;
  1503. }
  1504. unsigned BundleWidth = VectorizableTree[0].Scalars.size();
  1505. for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
  1506. int C = getEntryCost(&VectorizableTree[i]);
  1507. DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
  1508. << *VectorizableTree[i].Scalars[0] << " .\n");
  1509. Cost += C;
  1510. }
  1511. SmallSet<Value *, 16> ExtractCostCalculated;
  1512. int ExtractCost = 0;
  1513. for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
  1514. I != E; ++I) {
  1515. // We only add extract cost once for the same scalar.
  1516. if (!ExtractCostCalculated.insert(I->Scalar).second)
  1517. continue;
  1518. // Uses by ephemeral values are free (because the ephemeral value will be
  1519. // removed prior to code generation, and so the extraction will be
  1520. // removed as well).
  1521. if (EphValues.count(I->User))
  1522. continue;
  1523. VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
  1524. ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
  1525. I->Lane);
  1526. }
  1527. Cost += getSpillCost();
  1528. DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
  1529. return Cost + ExtractCost;
  1530. }
  1531. int BoUpSLP::getGatherCost(Type *Ty) {
  1532. int Cost = 0;
  1533. for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
  1534. Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
  1535. return Cost;
  1536. }
  1537. int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
  1538. // Find the type of the operands in VL.
  1539. Type *ScalarTy = VL[0]->getType();
  1540. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  1541. ScalarTy = SI->getValueOperand()->getType();
  1542. VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
  1543. // Find the cost of inserting/extracting values from the vector.
  1544. return getGatherCost(VecTy);
  1545. }
  1546. Value *BoUpSLP::getPointerOperand(Value *I) {
  1547. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  1548. return LI->getPointerOperand();
  1549. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  1550. return SI->getPointerOperand();
  1551. return nullptr;
  1552. }
  1553. unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
  1554. if (LoadInst *L = dyn_cast<LoadInst>(I))
  1555. return L->getPointerAddressSpace();
  1556. if (StoreInst *S = dyn_cast<StoreInst>(I))
  1557. return S->getPointerAddressSpace();
  1558. return -1;
  1559. }
  1560. bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
  1561. Value *PtrA = getPointerOperand(A);
  1562. Value *PtrB = getPointerOperand(B);
  1563. unsigned ASA = getAddressSpaceOperand(A);
  1564. unsigned ASB = getAddressSpaceOperand(B);
  1565. // Check that the address spaces match and that the pointers are valid.
  1566. if (!PtrA || !PtrB || (ASA != ASB))
  1567. return false;
  1568. // Make sure that A and B are different pointers of the same type.
  1569. if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
  1570. return false;
  1571. unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
  1572. Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
  1573. APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
  1574. APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
  1575. PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
  1576. PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
  1577. APInt OffsetDelta = OffsetB - OffsetA;
  1578. // Check if they are based on the same pointer. That makes the offsets
  1579. // sufficient.
  1580. if (PtrA == PtrB)
  1581. return OffsetDelta == Size;
  1582. // Compute the necessary base pointer delta to have the necessary final delta
  1583. // equal to the size.
  1584. APInt BaseDelta = Size - OffsetDelta;
  1585. // Otherwise compute the distance with SCEV between the base pointers.
  1586. const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
  1587. const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
  1588. const SCEV *C = SE->getConstant(BaseDelta);
  1589. const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
  1590. return X == PtrSCEVB;
  1591. }
  1592. // Reorder commutative operations in alternate shuffle if the resulting vectors
  1593. // are consecutive loads. This would allow us to vectorize the tree.
  1594. // If we have something like-
  1595. // load a[0] - load b[0]
  1596. // load b[1] + load a[1]
  1597. // load a[2] - load b[2]
  1598. // load a[3] + load b[3]
  1599. // Reordering the second load b[1] load a[1] would allow us to vectorize this
  1600. // code.
  1601. void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
  1602. SmallVectorImpl<Value *> &Left,
  1603. SmallVectorImpl<Value *> &Right) {
  1604. // Push left and right operands of binary operation into Left and Right
  1605. for (unsigned i = 0, e = VL.size(); i < e; ++i) {
  1606. Left.push_back(cast<Instruction>(VL[i])->getOperand(0));
  1607. Right.push_back(cast<Instruction>(VL[i])->getOperand(1));
  1608. }
  1609. // Reorder if we have a commutative operation and consecutive access
  1610. // are on either side of the alternate instructions.
  1611. for (unsigned j = 0; j < VL.size() - 1; ++j) {
  1612. if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
  1613. if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
  1614. Instruction *VL1 = cast<Instruction>(VL[j]);
  1615. Instruction *VL2 = cast<Instruction>(VL[j + 1]);
  1616. if (isConsecutiveAccess(L, L1) && VL1->isCommutative()) {
  1617. std::swap(Left[j], Right[j]);
  1618. continue;
  1619. } else if (isConsecutiveAccess(L, L1) && VL2->isCommutative()) {
  1620. std::swap(Left[j + 1], Right[j + 1]);
  1621. continue;
  1622. }
  1623. // else unchanged
  1624. }
  1625. }
  1626. if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
  1627. if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
  1628. Instruction *VL1 = cast<Instruction>(VL[j]);
  1629. Instruction *VL2 = cast<Instruction>(VL[j + 1]);
  1630. if (isConsecutiveAccess(L, L1) && VL1->isCommutative()) {
  1631. std::swap(Left[j], Right[j]);
  1632. continue;
  1633. } else if (isConsecutiveAccess(L, L1) && VL2->isCommutative()) {
  1634. std::swap(Left[j + 1], Right[j + 1]);
  1635. continue;
  1636. }
  1637. // else unchanged
  1638. }
  1639. }
  1640. }
  1641. }
  1642. void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
  1643. SmallVectorImpl<Value *> &Left,
  1644. SmallVectorImpl<Value *> &Right) {
  1645. SmallVector<Value *, 16> OrigLeft, OrigRight;
  1646. bool AllSameOpcodeLeft = true;
  1647. bool AllSameOpcodeRight = true;
  1648. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  1649. Instruction *I = cast<Instruction>(VL[i]);
  1650. Value *VLeft = I->getOperand(0);
  1651. Value *VRight = I->getOperand(1);
  1652. OrigLeft.push_back(VLeft);
  1653. OrigRight.push_back(VRight);
  1654. Instruction *ILeft = dyn_cast<Instruction>(VLeft);
  1655. Instruction *IRight = dyn_cast<Instruction>(VRight);
  1656. // Check whether all operands on one side have the same opcode. In this case
  1657. // we want to preserve the original order and not make things worse by
  1658. // reordering.
  1659. if (i && AllSameOpcodeLeft && ILeft) {
  1660. if (Instruction *PLeft = dyn_cast<Instruction>(OrigLeft[i - 1])) {
  1661. if (PLeft->getOpcode() != ILeft->getOpcode())
  1662. AllSameOpcodeLeft = false;
  1663. } else
  1664. AllSameOpcodeLeft = false;
  1665. }
  1666. if (i && AllSameOpcodeRight && IRight) {
  1667. if (Instruction *PRight = dyn_cast<Instruction>(OrigRight[i - 1])) {
  1668. if (PRight->getOpcode() != IRight->getOpcode())
  1669. AllSameOpcodeRight = false;
  1670. } else
  1671. AllSameOpcodeRight = false;
  1672. }
  1673. // Sort two opcodes. In the code below we try to preserve the ability to use
  1674. // broadcast of values instead of individual inserts.
  1675. // vl1 = load
  1676. // vl2 = phi
  1677. // vr1 = load
  1678. // vr2 = vr2
  1679. // = vl1 x vr1
  1680. // = vl2 x vr2
  1681. // If we just sorted according to opcode we would leave the first line in
  1682. // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
  1683. // = vl1 x vr1
  1684. // = vr2 x vl2
  1685. // Because vr2 and vr1 are from the same load we loose the opportunity of a
  1686. // broadcast for the packed right side in the backend: we have [vr1, vl2]
  1687. // instead of [vr1, vr2=vr1].
  1688. if (ILeft && IRight) {
  1689. if (!i && ILeft->getOpcode() > IRight->getOpcode()) {
  1690. Left.push_back(IRight);
  1691. Right.push_back(ILeft);
  1692. } else if (i && ILeft->getOpcode() > IRight->getOpcode() &&
  1693. Right[i - 1] != IRight) {
  1694. // Try not to destroy a broad cast for no apparent benefit.
  1695. Left.push_back(IRight);
  1696. Right.push_back(ILeft);
  1697. } else if (i && ILeft->getOpcode() == IRight->getOpcode() &&
  1698. Right[i - 1] == ILeft) {
  1699. // Try preserve broadcasts.
  1700. Left.push_back(IRight);
  1701. Right.push_back(ILeft);
  1702. } else if (i && ILeft->getOpcode() == IRight->getOpcode() &&
  1703. Left[i - 1] == IRight) {
  1704. // Try preserve broadcasts.
  1705. Left.push_back(IRight);
  1706. Right.push_back(ILeft);
  1707. } else {
  1708. Left.push_back(ILeft);
  1709. Right.push_back(IRight);
  1710. }
  1711. continue;
  1712. }
  1713. // One opcode, put the instruction on the right.
  1714. if (ILeft) {
  1715. Left.push_back(VRight);
  1716. Right.push_back(ILeft);
  1717. continue;
  1718. }
  1719. Left.push_back(VLeft);
  1720. Right.push_back(VRight);
  1721. }
  1722. bool LeftBroadcast = isSplat(Left);
  1723. bool RightBroadcast = isSplat(Right);
  1724. // If operands end up being broadcast return this operand order.
  1725. if (LeftBroadcast || RightBroadcast)
  1726. return;
  1727. // Don't reorder if the operands where good to begin.
  1728. if (AllSameOpcodeRight || AllSameOpcodeLeft) {
  1729. Left = OrigLeft;
  1730. Right = OrigRight;
  1731. }
  1732. // Finally check if we can get longer vectorizable chain by reordering
  1733. // without breaking the good operand order detected above.
  1734. // E.g. If we have something like-
  1735. // load a[0] load b[0]
  1736. // load b[1] load a[1]
  1737. // load a[2] load b[2]
  1738. // load a[3] load b[3]
  1739. // Reordering the second load b[1] load a[1] would allow us to vectorize
  1740. // this code and we still retain AllSameOpcode property.
  1741. // FIXME: This load reordering might break AllSameOpcode in some rare cases
  1742. // such as-
  1743. // add a[0],c[0] load b[0]
  1744. // add a[1],c[2] load b[1]
  1745. // b[2] load b[2]
  1746. // add a[3],c[3] load b[3]
  1747. for (unsigned j = 0; j < VL.size() - 1; ++j) {
  1748. if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
  1749. if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
  1750. if (isConsecutiveAccess(L, L1)) {
  1751. std::swap(Left[j + 1], Right[j + 1]);
  1752. continue;
  1753. }
  1754. }
  1755. }
  1756. if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
  1757. if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
  1758. if (isConsecutiveAccess(L, L1)) {
  1759. std::swap(Left[j + 1], Right[j + 1]);
  1760. continue;
  1761. }
  1762. }
  1763. }
  1764. // else unchanged
  1765. }
  1766. }
  1767. void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
  1768. Instruction *VL0 = cast<Instruction>(VL[0]);
  1769. BasicBlock::iterator NextInst = VL0;
  1770. ++NextInst;
  1771. Builder.SetInsertPoint(VL0->getParent(), NextInst);
  1772. Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
  1773. }
  1774. Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
  1775. Value *Vec = UndefValue::get(Ty);
  1776. // Generate the 'InsertElement' instruction.
  1777. for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
  1778. Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
  1779. if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
  1780. GatherSeq.insert(Insrt);
  1781. CSEBlocks.insert(Insrt->getParent());
  1782. // Add to our 'need-to-extract' list.
  1783. if (ScalarToTreeEntry.count(VL[i])) {
  1784. int Idx = ScalarToTreeEntry[VL[i]];
  1785. TreeEntry *E = &VectorizableTree[Idx];
  1786. // Find which lane we need to extract.
  1787. int FoundLane = -1;
  1788. for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
  1789. // Is this the lane of the scalar that we are looking for ?
  1790. if (E->Scalars[Lane] == VL[i]) {
  1791. FoundLane = Lane;
  1792. break;
  1793. }
  1794. }
  1795. assert(FoundLane >= 0 && "Could not find the correct lane");
  1796. ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
  1797. }
  1798. }
  1799. }
  1800. return Vec;
  1801. }
  1802. Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
  1803. SmallDenseMap<Value*, int>::const_iterator Entry
  1804. = ScalarToTreeEntry.find(VL[0]);
  1805. if (Entry != ScalarToTreeEntry.end()) {
  1806. int Idx = Entry->second;
  1807. const TreeEntry *En = &VectorizableTree[Idx];
  1808. if (En->isSame(VL) && En->VectorizedValue)
  1809. return En->VectorizedValue;
  1810. }
  1811. return nullptr;
  1812. }
  1813. Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
  1814. if (ScalarToTreeEntry.count(VL[0])) {
  1815. int Idx = ScalarToTreeEntry[VL[0]];
  1816. TreeEntry *E = &VectorizableTree[Idx];
  1817. if (E->isSame(VL))
  1818. return vectorizeTree(E);
  1819. }
  1820. Type *ScalarTy = VL[0]->getType();
  1821. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  1822. ScalarTy = SI->getValueOperand()->getType();
  1823. VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
  1824. return Gather(VL, VecTy);
  1825. }
  1826. Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
  1827. IRBuilder<>::InsertPointGuard Guard(Builder);
  1828. if (E->VectorizedValue) {
  1829. DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
  1830. return E->VectorizedValue;
  1831. }
  1832. Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
  1833. Type *ScalarTy = VL0->getType();
  1834. if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
  1835. ScalarTy = SI->getValueOperand()->getType();
  1836. VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
  1837. if (E->NeedToGather) {
  1838. setInsertPointAfterBundle(E->Scalars);
  1839. return Gather(E->Scalars, VecTy);
  1840. }
  1841. unsigned Opcode = getSameOpcode(E->Scalars);
  1842. switch (Opcode) {
  1843. case Instruction::PHI: {
  1844. PHINode *PH = dyn_cast<PHINode>(VL0);
  1845. Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
  1846. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  1847. PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
  1848. E->VectorizedValue = NewPhi;
  1849. // PHINodes may have multiple entries from the same block. We want to
  1850. // visit every block once.
  1851. SmallSet<BasicBlock*, 4> VisitedBBs;
  1852. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  1853. ValueList Operands;
  1854. BasicBlock *IBB = PH->getIncomingBlock(i);
  1855. if (!VisitedBBs.insert(IBB).second) {
  1856. NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
  1857. continue;
  1858. }
  1859. // Prepare the operand vector.
  1860. for (unsigned j = 0; j < E->Scalars.size(); ++j)
  1861. Operands.push_back(cast<PHINode>(E->Scalars[j])->
  1862. getIncomingValueForBlock(IBB));
  1863. Builder.SetInsertPoint(IBB->getTerminator());
  1864. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  1865. Value *Vec = vectorizeTree(Operands);
  1866. NewPhi->addIncoming(Vec, IBB);
  1867. }
  1868. assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
  1869. "Invalid number of incoming values");
  1870. return NewPhi;
  1871. }
  1872. case Instruction::ExtractElement: {
  1873. if (CanReuseExtract(E->Scalars)) {
  1874. Value *V = VL0->getOperand(0);
  1875. E->VectorizedValue = V;
  1876. return V;
  1877. }
  1878. return Gather(E->Scalars, VecTy);
  1879. }
  1880. case Instruction::ZExt:
  1881. case Instruction::SExt:
  1882. case Instruction::FPToUI:
  1883. case Instruction::FPToSI:
  1884. case Instruction::FPExt:
  1885. case Instruction::PtrToInt:
  1886. case Instruction::IntToPtr:
  1887. case Instruction::SIToFP:
  1888. case Instruction::UIToFP:
  1889. case Instruction::Trunc:
  1890. case Instruction::FPTrunc:
  1891. case Instruction::BitCast: {
  1892. ValueList INVL;
  1893. for (int i = 0, e = E->Scalars.size(); i < e; ++i)
  1894. INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
  1895. setInsertPointAfterBundle(E->Scalars);
  1896. Value *InVec = vectorizeTree(INVL);
  1897. if (Value *V = alreadyVectorized(E->Scalars))
  1898. return V;
  1899. CastInst *CI = dyn_cast<CastInst>(VL0);
  1900. Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
  1901. E->VectorizedValue = V;
  1902. ++NumVectorInstructions;
  1903. return V;
  1904. }
  1905. case Instruction::FCmp:
  1906. case Instruction::ICmp: {
  1907. ValueList LHSV, RHSV;
  1908. for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
  1909. LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
  1910. RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
  1911. }
  1912. setInsertPointAfterBundle(E->Scalars);
  1913. Value *L = vectorizeTree(LHSV);
  1914. Value *R = vectorizeTree(RHSV);
  1915. if (Value *V = alreadyVectorized(E->Scalars))
  1916. return V;
  1917. CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
  1918. Value *V;
  1919. if (Opcode == Instruction::FCmp)
  1920. V = Builder.CreateFCmp(P0, L, R);
  1921. else
  1922. V = Builder.CreateICmp(P0, L, R);
  1923. E->VectorizedValue = V;
  1924. ++NumVectorInstructions;
  1925. return V;
  1926. }
  1927. case Instruction::Select: {
  1928. ValueList TrueVec, FalseVec, CondVec;
  1929. for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
  1930. CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
  1931. TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
  1932. FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
  1933. }
  1934. setInsertPointAfterBundle(E->Scalars);
  1935. Value *Cond = vectorizeTree(CondVec);
  1936. Value *True = vectorizeTree(TrueVec);
  1937. Value *False = vectorizeTree(FalseVec);
  1938. if (Value *V = alreadyVectorized(E->Scalars))
  1939. return V;
  1940. Value *V = Builder.CreateSelect(Cond, True, False);
  1941. E->VectorizedValue = V;
  1942. ++NumVectorInstructions;
  1943. return V;
  1944. }
  1945. case Instruction::Add:
  1946. case Instruction::FAdd:
  1947. case Instruction::Sub:
  1948. case Instruction::FSub:
  1949. case Instruction::Mul:
  1950. case Instruction::FMul:
  1951. case Instruction::UDiv:
  1952. case Instruction::SDiv:
  1953. case Instruction::FDiv:
  1954. case Instruction::URem:
  1955. case Instruction::SRem:
  1956. case Instruction::FRem:
  1957. case Instruction::Shl:
  1958. case Instruction::LShr:
  1959. case Instruction::AShr:
  1960. case Instruction::And:
  1961. case Instruction::Or:
  1962. case Instruction::Xor: {
  1963. ValueList LHSVL, RHSVL;
  1964. if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
  1965. reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
  1966. else
  1967. for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
  1968. LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
  1969. RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
  1970. }
  1971. setInsertPointAfterBundle(E->Scalars);
  1972. Value *LHS = vectorizeTree(LHSVL);
  1973. Value *RHS = vectorizeTree(RHSVL);
  1974. if (LHS == RHS && isa<Instruction>(LHS)) {
  1975. assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
  1976. }
  1977. if (Value *V = alreadyVectorized(E->Scalars))
  1978. return V;
  1979. BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
  1980. Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
  1981. E->VectorizedValue = V;
  1982. propagateIRFlags(E->VectorizedValue, E->Scalars);
  1983. ++NumVectorInstructions;
  1984. if (Instruction *I = dyn_cast<Instruction>(V))
  1985. return propagateMetadata(I, E->Scalars);
  1986. return V;
  1987. }
  1988. case Instruction::Load: {
  1989. // Loads are inserted at the head of the tree because we don't want to
  1990. // sink them all the way down past store instructions.
  1991. setInsertPointAfterBundle(E->Scalars);
  1992. LoadInst *LI = cast<LoadInst>(VL0);
  1993. Type *ScalarLoadTy = LI->getType();
  1994. unsigned AS = LI->getPointerAddressSpace();
  1995. Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
  1996. VecTy->getPointerTo(AS));
  1997. // The pointer operand uses an in-tree scalar so we add the new BitCast to
  1998. // ExternalUses list to make sure that an extract will be generated in the
  1999. // future.
  2000. if (ScalarToTreeEntry.count(LI->getPointerOperand()))
  2001. ExternalUses.push_back(
  2002. ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
  2003. unsigned Alignment = LI->getAlignment();
  2004. LI = Builder.CreateLoad(VecPtr);
  2005. if (!Alignment)
  2006. Alignment = DL->getABITypeAlignment(ScalarLoadTy);
  2007. LI->setAlignment(Alignment);
  2008. E->VectorizedValue = LI;
  2009. ++NumVectorInstructions;
  2010. return propagateMetadata(LI, E->Scalars);
  2011. }
  2012. case Instruction::Store: {
  2013. StoreInst *SI = cast<StoreInst>(VL0);
  2014. unsigned Alignment = SI->getAlignment();
  2015. unsigned AS = SI->getPointerAddressSpace();
  2016. ValueList ValueOp;
  2017. for (int i = 0, e = E->Scalars.size(); i < e; ++i)
  2018. ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
  2019. setInsertPointAfterBundle(E->Scalars);
  2020. Value *VecValue = vectorizeTree(ValueOp);
  2021. Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
  2022. VecTy->getPointerTo(AS));
  2023. StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
  2024. // The pointer operand uses an in-tree scalar so we add the new BitCast to
  2025. // ExternalUses list to make sure that an extract will be generated in the
  2026. // future.
  2027. if (ScalarToTreeEntry.count(SI->getPointerOperand()))
  2028. ExternalUses.push_back(
  2029. ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
  2030. if (!Alignment)
  2031. Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
  2032. S->setAlignment(Alignment);
  2033. E->VectorizedValue = S;
  2034. ++NumVectorInstructions;
  2035. return propagateMetadata(S, E->Scalars);
  2036. }
  2037. case Instruction::GetElementPtr: {
  2038. setInsertPointAfterBundle(E->Scalars);
  2039. ValueList Op0VL;
  2040. for (int i = 0, e = E->Scalars.size(); i < e; ++i)
  2041. Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
  2042. Value *Op0 = vectorizeTree(Op0VL);
  2043. std::vector<Value *> OpVecs;
  2044. for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
  2045. ++j) {
  2046. ValueList OpVL;
  2047. for (int i = 0, e = E->Scalars.size(); i < e; ++i)
  2048. OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
  2049. Value *OpVec = vectorizeTree(OpVL);
  2050. OpVecs.push_back(OpVec);
  2051. }
  2052. Value *V = Builder.CreateGEP(Op0, OpVecs);
  2053. E->VectorizedValue = V;
  2054. ++NumVectorInstructions;
  2055. if (Instruction *I = dyn_cast<Instruction>(V))
  2056. return propagateMetadata(I, E->Scalars);
  2057. return V;
  2058. }
  2059. case Instruction::Call: {
  2060. CallInst *CI = cast<CallInst>(VL0);
  2061. setInsertPointAfterBundle(E->Scalars);
  2062. Function *FI;
  2063. Intrinsic::ID IID = Intrinsic::not_intrinsic;
  2064. Value *ScalarArg = nullptr;
  2065. if (CI && (FI = CI->getCalledFunction())) {
  2066. IID = (Intrinsic::ID) FI->getIntrinsicID();
  2067. }
  2068. std::vector<Value *> OpVecs;
  2069. for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
  2070. ValueList OpVL;
  2071. // ctlz,cttz and powi are special intrinsics whose second argument is
  2072. // a scalar. This argument should not be vectorized.
  2073. if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
  2074. CallInst *CEI = cast<CallInst>(E->Scalars[0]);
  2075. ScalarArg = CEI->getArgOperand(j);
  2076. OpVecs.push_back(CEI->getArgOperand(j));
  2077. continue;
  2078. }
  2079. for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
  2080. CallInst *CEI = cast<CallInst>(E->Scalars[i]);
  2081. OpVL.push_back(CEI->getArgOperand(j));
  2082. }
  2083. Value *OpVec = vectorizeTree(OpVL);
  2084. DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
  2085. OpVecs.push_back(OpVec);
  2086. }
  2087. Module *M = F->getParent();
  2088. Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
  2089. Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
  2090. Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
  2091. Value *V = Builder.CreateCall(CF, OpVecs);
  2092. // The scalar argument uses an in-tree scalar so we add the new vectorized
  2093. // call to ExternalUses list to make sure that an extract will be
  2094. // generated in the future.
  2095. if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
  2096. ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
  2097. E->VectorizedValue = V;
  2098. ++NumVectorInstructions;
  2099. return V;
  2100. }
  2101. case Instruction::ShuffleVector: {
  2102. ValueList LHSVL, RHSVL;
  2103. assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand");
  2104. reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
  2105. setInsertPointAfterBundle(E->Scalars);
  2106. Value *LHS = vectorizeTree(LHSVL);
  2107. Value *RHS = vectorizeTree(RHSVL);
  2108. if (Value *V = alreadyVectorized(E->Scalars))
  2109. return V;
  2110. // Create a vector of LHS op1 RHS
  2111. BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
  2112. Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
  2113. // Create a vector of LHS op2 RHS
  2114. Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
  2115. BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
  2116. Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
  2117. // Create shuffle to take alternate operations from the vector.
  2118. // Also, gather up odd and even scalar ops to propagate IR flags to
  2119. // each vector operation.
  2120. ValueList OddScalars, EvenScalars;
  2121. unsigned e = E->Scalars.size();
  2122. SmallVector<Constant *, 8> Mask(e);
  2123. for (unsigned i = 0; i < e; ++i) {
  2124. if (i & 1) {
  2125. Mask[i] = Builder.getInt32(e + i);
  2126. OddScalars.push_back(E->Scalars[i]);
  2127. } else {
  2128. Mask[i] = Builder.getInt32(i);
  2129. EvenScalars.push_back(E->Scalars[i]);
  2130. }
  2131. }
  2132. Value *ShuffleMask = ConstantVector::get(Mask);
  2133. propagateIRFlags(V0, EvenScalars);
  2134. propagateIRFlags(V1, OddScalars);
  2135. Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
  2136. E->VectorizedValue = V;
  2137. ++NumVectorInstructions;
  2138. if (Instruction *I = dyn_cast<Instruction>(V))
  2139. return propagateMetadata(I, E->Scalars);
  2140. return V;
  2141. }
  2142. default:
  2143. llvm_unreachable("unknown inst");
  2144. }
  2145. return nullptr;
  2146. }
  2147. Value *BoUpSLP::vectorizeTree() {
  2148. // All blocks must be scheduled before any instructions are inserted.
  2149. for (auto &BSIter : BlocksSchedules) {
  2150. scheduleBlock(BSIter.second.get());
  2151. }
  2152. Builder.SetInsertPoint(F->getEntryBlock().begin());
  2153. vectorizeTree(&VectorizableTree[0]);
  2154. DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
  2155. // Extract all of the elements with the external uses.
  2156. for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
  2157. it != e; ++it) {
  2158. Value *Scalar = it->Scalar;
  2159. llvm::User *User = it->User;
  2160. // Skip users that we already RAUW. This happens when one instruction
  2161. // has multiple uses of the same value.
  2162. if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
  2163. Scalar->user_end())
  2164. continue;
  2165. assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
  2166. int Idx = ScalarToTreeEntry[Scalar];
  2167. TreeEntry *E = &VectorizableTree[Idx];
  2168. assert(!E->NeedToGather && "Extracting from a gather list");
  2169. Value *Vec = E->VectorizedValue;
  2170. assert(Vec && "Can't find vectorizable value");
  2171. Value *Lane = Builder.getInt32(it->Lane);
  2172. // Generate extracts for out-of-tree users.
  2173. // Find the insertion point for the extractelement lane.
  2174. if (isa<Instruction>(Vec)){
  2175. if (PHINode *PH = dyn_cast<PHINode>(User)) {
  2176. for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
  2177. if (PH->getIncomingValue(i) == Scalar) {
  2178. Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
  2179. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  2180. CSEBlocks.insert(PH->getIncomingBlock(i));
  2181. PH->setOperand(i, Ex);
  2182. }
  2183. }
  2184. } else {
  2185. Builder.SetInsertPoint(cast<Instruction>(User));
  2186. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  2187. CSEBlocks.insert(cast<Instruction>(User)->getParent());
  2188. User->replaceUsesOfWith(Scalar, Ex);
  2189. }
  2190. } else {
  2191. Builder.SetInsertPoint(F->getEntryBlock().begin());
  2192. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  2193. CSEBlocks.insert(&F->getEntryBlock());
  2194. User->replaceUsesOfWith(Scalar, Ex);
  2195. }
  2196. DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
  2197. }
  2198. // For each vectorized value:
  2199. for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
  2200. TreeEntry *Entry = &VectorizableTree[EIdx];
  2201. // For each lane:
  2202. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  2203. Value *Scalar = Entry->Scalars[Lane];
  2204. // No need to handle users of gathered values.
  2205. if (Entry->NeedToGather)
  2206. continue;
  2207. assert(Entry->VectorizedValue && "Can't find vectorizable value");
  2208. Type *Ty = Scalar->getType();
  2209. if (!Ty->isVoidTy()) {
  2210. #ifndef NDEBUG
  2211. for (User *U : Scalar->users()) {
  2212. DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
  2213. assert((ScalarToTreeEntry.count(U) ||
  2214. // It is legal to replace users in the ignorelist by undef.
  2215. (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
  2216. UserIgnoreList.end())) &&
  2217. "Replacing out-of-tree value with undef");
  2218. }
  2219. #endif
  2220. Value *Undef = UndefValue::get(Ty);
  2221. Scalar->replaceAllUsesWith(Undef);
  2222. }
  2223. DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
  2224. eraseInstruction(cast<Instruction>(Scalar));
  2225. }
  2226. }
  2227. Builder.ClearInsertionPoint();
  2228. return VectorizableTree[0].VectorizedValue;
  2229. }
  2230. void BoUpSLP::optimizeGatherSequence() {
  2231. DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
  2232. << " gather sequences instructions.\n");
  2233. // LICM InsertElementInst sequences.
  2234. for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
  2235. e = GatherSeq.end(); it != e; ++it) {
  2236. InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
  2237. if (!Insert)
  2238. continue;
  2239. // Check if this block is inside a loop.
  2240. Loop *L = LI->getLoopFor(Insert->getParent());
  2241. if (!L)
  2242. continue;
  2243. // Check if it has a preheader.
  2244. BasicBlock *PreHeader = L->getLoopPreheader();
  2245. if (!PreHeader)
  2246. continue;
  2247. // If the vector or the element that we insert into it are
  2248. // instructions that are defined in this basic block then we can't
  2249. // hoist this instruction.
  2250. Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
  2251. Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
  2252. if (CurrVec && L->contains(CurrVec))
  2253. continue;
  2254. if (NewElem && L->contains(NewElem))
  2255. continue;
  2256. // We can hoist this instruction. Move it to the pre-header.
  2257. Insert->moveBefore(PreHeader->getTerminator());
  2258. }
  2259. // Make a list of all reachable blocks in our CSE queue.
  2260. SmallVector<const DomTreeNode *, 8> CSEWorkList;
  2261. CSEWorkList.reserve(CSEBlocks.size());
  2262. for (BasicBlock *BB : CSEBlocks)
  2263. if (DomTreeNode *N = DT->getNode(BB)) {
  2264. assert(DT->isReachableFromEntry(N));
  2265. CSEWorkList.push_back(N);
  2266. }
  2267. // Sort blocks by domination. This ensures we visit a block after all blocks
  2268. // dominating it are visited.
  2269. std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
  2270. [this](const DomTreeNode *A, const DomTreeNode *B) {
  2271. return DT->properlyDominates(A, B);
  2272. });
  2273. // Perform O(N^2) search over the gather sequences and merge identical
  2274. // instructions. TODO: We can further optimize this scan if we split the
  2275. // instructions into different buckets based on the insert lane.
  2276. SmallVector<Instruction *, 16> Visited;
  2277. for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
  2278. assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
  2279. "Worklist not sorted properly!");
  2280. BasicBlock *BB = (*I)->getBlock();
  2281. // For all instructions in blocks containing gather sequences:
  2282. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
  2283. Instruction *In = it++;
  2284. if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
  2285. continue;
  2286. // Check if we can replace this instruction with any of the
  2287. // visited instructions.
  2288. for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
  2289. ve = Visited.end();
  2290. v != ve; ++v) {
  2291. if (In->isIdenticalTo(*v) &&
  2292. DT->dominates((*v)->getParent(), In->getParent())) {
  2293. In->replaceAllUsesWith(*v);
  2294. eraseInstruction(In);
  2295. In = nullptr;
  2296. break;
  2297. }
  2298. }
  2299. if (In) {
  2300. assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
  2301. Visited.push_back(In);
  2302. }
  2303. }
  2304. }
  2305. CSEBlocks.clear();
  2306. GatherSeq.clear();
  2307. }
  2308. // Groups the instructions to a bundle (which is then a single scheduling entity)
  2309. // and schedules instructions until the bundle gets ready.
  2310. bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
  2311. BoUpSLP *SLP) {
  2312. if (isa<PHINode>(VL[0]))
  2313. return true;
  2314. // Initialize the instruction bundle.
  2315. Instruction *OldScheduleEnd = ScheduleEnd;
  2316. ScheduleData *PrevInBundle = nullptr;
  2317. ScheduleData *Bundle = nullptr;
  2318. bool ReSchedule = false;
  2319. DEBUG(dbgs() << "SLP: bundle: " << *VL[0] << "\n");
  2320. for (Value *V : VL) {
  2321. extendSchedulingRegion(V);
  2322. ScheduleData *BundleMember = getScheduleData(V);
  2323. assert(BundleMember &&
  2324. "no ScheduleData for bundle member (maybe not in same basic block)");
  2325. if (BundleMember->IsScheduled) {
  2326. // A bundle member was scheduled as single instruction before and now
  2327. // needs to be scheduled as part of the bundle. We just get rid of the
  2328. // existing schedule.
  2329. DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
  2330. << " was already scheduled\n");
  2331. ReSchedule = true;
  2332. }
  2333. assert(BundleMember->isSchedulingEntity() &&
  2334. "bundle member already part of other bundle");
  2335. if (PrevInBundle) {
  2336. PrevInBundle->NextInBundle = BundleMember;
  2337. } else {
  2338. Bundle = BundleMember;
  2339. }
  2340. BundleMember->UnscheduledDepsInBundle = 0;
  2341. Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
  2342. // Group the instructions to a bundle.
  2343. BundleMember->FirstInBundle = Bundle;
  2344. PrevInBundle = BundleMember;
  2345. }
  2346. if (ScheduleEnd != OldScheduleEnd) {
  2347. // The scheduling region got new instructions at the lower end (or it is a
  2348. // new region for the first bundle). This makes it necessary to
  2349. // recalculate all dependencies.
  2350. // It is seldom that this needs to be done a second time after adding the
  2351. // initial bundle to the region.
  2352. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  2353. ScheduleData *SD = getScheduleData(I);
  2354. SD->clearDependencies();
  2355. }
  2356. ReSchedule = true;
  2357. }
  2358. if (ReSchedule) {
  2359. resetSchedule();
  2360. initialFillReadyList(ReadyInsts);
  2361. }
  2362. DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
  2363. << BB->getName() << "\n");
  2364. calculateDependencies(Bundle, true, SLP);
  2365. // Now try to schedule the new bundle. As soon as the bundle is "ready" it
  2366. // means that there are no cyclic dependencies and we can schedule it.
  2367. // Note that's important that we don't "schedule" the bundle yet (see
  2368. // cancelScheduling).
  2369. while (!Bundle->isReady() && !ReadyInsts.empty()) {
  2370. ScheduleData *pickedSD = ReadyInsts.back();
  2371. ReadyInsts.pop_back();
  2372. if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
  2373. schedule(pickedSD, ReadyInsts);
  2374. }
  2375. }
  2376. return Bundle->isReady();
  2377. }
  2378. void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
  2379. if (isa<PHINode>(VL[0]))
  2380. return;
  2381. ScheduleData *Bundle = getScheduleData(VL[0]);
  2382. DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
  2383. assert(!Bundle->IsScheduled &&
  2384. "Can't cancel bundle which is already scheduled");
  2385. assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
  2386. "tried to unbundle something which is not a bundle");
  2387. // Un-bundle: make single instructions out of the bundle.
  2388. ScheduleData *BundleMember = Bundle;
  2389. while (BundleMember) {
  2390. assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
  2391. BundleMember->FirstInBundle = BundleMember;
  2392. ScheduleData *Next = BundleMember->NextInBundle;
  2393. BundleMember->NextInBundle = nullptr;
  2394. BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
  2395. if (BundleMember->UnscheduledDepsInBundle == 0) {
  2396. ReadyInsts.insert(BundleMember);
  2397. }
  2398. BundleMember = Next;
  2399. }
  2400. }
  2401. void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
  2402. if (getScheduleData(V))
  2403. return;
  2404. Instruction *I = dyn_cast<Instruction>(V);
  2405. assert(I && "bundle member must be an instruction");
  2406. assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
  2407. if (!ScheduleStart) {
  2408. // It's the first instruction in the new region.
  2409. initScheduleData(I, I->getNextNode(), nullptr, nullptr);
  2410. ScheduleStart = I;
  2411. ScheduleEnd = I->getNextNode();
  2412. assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
  2413. DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
  2414. return;
  2415. }
  2416. // Search up and down at the same time, because we don't know if the new
  2417. // instruction is above or below the existing scheduling region.
  2418. BasicBlock::reverse_iterator UpIter(ScheduleStart);
  2419. BasicBlock::reverse_iterator UpperEnd = BB->rend();
  2420. BasicBlock::iterator DownIter(ScheduleEnd);
  2421. BasicBlock::iterator LowerEnd = BB->end();
  2422. for (;;) {
  2423. if (UpIter != UpperEnd) {
  2424. if (&*UpIter == I) {
  2425. initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
  2426. ScheduleStart = I;
  2427. DEBUG(dbgs() << "SLP: extend schedule region start to " << *I << "\n");
  2428. return;
  2429. }
  2430. UpIter++;
  2431. }
  2432. if (DownIter != LowerEnd) {
  2433. if (&*DownIter == I) {
  2434. initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
  2435. nullptr);
  2436. ScheduleEnd = I->getNextNode();
  2437. assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
  2438. DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
  2439. return;
  2440. }
  2441. DownIter++;
  2442. }
  2443. assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
  2444. "instruction not found in block");
  2445. }
  2446. }
  2447. void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
  2448. Instruction *ToI,
  2449. ScheduleData *PrevLoadStore,
  2450. ScheduleData *NextLoadStore) {
  2451. ScheduleData *CurrentLoadStore = PrevLoadStore;
  2452. for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
  2453. ScheduleData *SD = ScheduleDataMap[I];
  2454. if (!SD) {
  2455. // Allocate a new ScheduleData for the instruction.
  2456. if (ChunkPos >= ChunkSize) {
  2457. ScheduleDataChunks.push_back(
  2458. llvm::make_unique<ScheduleData[]>(ChunkSize));
  2459. ChunkPos = 0;
  2460. }
  2461. SD = &(ScheduleDataChunks.back()[ChunkPos++]);
  2462. ScheduleDataMap[I] = SD;
  2463. SD->Inst = I;
  2464. }
  2465. assert(!isInSchedulingRegion(SD) &&
  2466. "new ScheduleData already in scheduling region");
  2467. SD->init(SchedulingRegionID);
  2468. if (I->mayReadOrWriteMemory()) {
  2469. // Update the linked list of memory accessing instructions.
  2470. if (CurrentLoadStore) {
  2471. CurrentLoadStore->NextLoadStore = SD;
  2472. } else {
  2473. FirstLoadStoreInRegion = SD;
  2474. }
  2475. CurrentLoadStore = SD;
  2476. }
  2477. }
  2478. if (NextLoadStore) {
  2479. if (CurrentLoadStore)
  2480. CurrentLoadStore->NextLoadStore = NextLoadStore;
  2481. } else {
  2482. LastLoadStoreInRegion = CurrentLoadStore;
  2483. }
  2484. }
  2485. void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
  2486. bool InsertInReadyList,
  2487. BoUpSLP *SLP) {
  2488. assert(SD->isSchedulingEntity());
  2489. SmallVector<ScheduleData *, 10> WorkList;
  2490. WorkList.push_back(SD);
  2491. while (!WorkList.empty()) {
  2492. ScheduleData *SD = WorkList.back();
  2493. WorkList.pop_back();
  2494. ScheduleData *BundleMember = SD;
  2495. while (BundleMember) {
  2496. assert(isInSchedulingRegion(BundleMember));
  2497. if (!BundleMember->hasValidDependencies()) {
  2498. DEBUG(dbgs() << "SLP: update deps of " << *BundleMember << "\n");
  2499. BundleMember->Dependencies = 0;
  2500. BundleMember->resetUnscheduledDeps();
  2501. // Handle def-use chain dependencies.
  2502. for (User *U : BundleMember->Inst->users()) {
  2503. if (isa<Instruction>(U)) {
  2504. ScheduleData *UseSD = getScheduleData(U);
  2505. if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
  2506. BundleMember->Dependencies++;
  2507. ScheduleData *DestBundle = UseSD->FirstInBundle;
  2508. if (!DestBundle->IsScheduled) {
  2509. BundleMember->incrementUnscheduledDeps(1);
  2510. }
  2511. if (!DestBundle->hasValidDependencies()) {
  2512. WorkList.push_back(DestBundle);
  2513. }
  2514. }
  2515. } else {
  2516. // I'm not sure if this can ever happen. But we need to be safe.
  2517. // This lets the instruction/bundle never be scheduled and eventally
  2518. // disable vectorization.
  2519. BundleMember->Dependencies++;
  2520. BundleMember->incrementUnscheduledDeps(1);
  2521. }
  2522. }
  2523. // Handle the memory dependencies.
  2524. ScheduleData *DepDest = BundleMember->NextLoadStore;
  2525. if (DepDest) {
  2526. Instruction *SrcInst = BundleMember->Inst;
  2527. AliasAnalysis::Location SrcLoc = getLocation(SrcInst, SLP->AA);
  2528. bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
  2529. unsigned numAliased = 0;
  2530. unsigned DistToSrc = 1;
  2531. while (DepDest) {
  2532. assert(isInSchedulingRegion(DepDest));
  2533. // We have two limits to reduce the complexity:
  2534. // 1) AliasedCheckLimit: It's a small limit to reduce calls to
  2535. // SLP->isAliased (which is the expensive part in this loop).
  2536. // 2) MaxMemDepDistance: It's for very large blocks and it aborts
  2537. // the whole loop (even if the loop is fast, it's quadratic).
  2538. // It's important for the loop break condition (see below) to
  2539. // check this limit even between two read-only instructions.
  2540. if (DistToSrc >= MaxMemDepDistance ||
  2541. ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
  2542. (numAliased >= AliasedCheckLimit ||
  2543. SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
  2544. // We increment the counter only if the locations are aliased
  2545. // (instead of counting all alias checks). This gives a better
  2546. // balance between reduced runtime and accurate dependencies.
  2547. numAliased++;
  2548. DepDest->MemoryDependencies.push_back(BundleMember);
  2549. BundleMember->Dependencies++;
  2550. ScheduleData *DestBundle = DepDest->FirstInBundle;
  2551. if (!DestBundle->IsScheduled) {
  2552. BundleMember->incrementUnscheduledDeps(1);
  2553. }
  2554. if (!DestBundle->hasValidDependencies()) {
  2555. WorkList.push_back(DestBundle);
  2556. }
  2557. }
  2558. DepDest = DepDest->NextLoadStore;
  2559. // Example, explaining the loop break condition: Let's assume our
  2560. // starting instruction is i0 and MaxMemDepDistance = 3.
  2561. //
  2562. // +--------v--v--v
  2563. // i0,i1,i2,i3,i4,i5,i6,i7,i8
  2564. // +--------^--^--^
  2565. //
  2566. // MaxMemDepDistance let us stop alias-checking at i3 and we add
  2567. // dependencies from i0 to i3,i4,.. (even if they are not aliased).
  2568. // Previously we already added dependencies from i3 to i6,i7,i8
  2569. // (because of MaxMemDepDistance). As we added a dependency from
  2570. // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
  2571. // and we can abort this loop at i6.
  2572. if (DistToSrc >= 2 * MaxMemDepDistance)
  2573. break;
  2574. DistToSrc++;
  2575. }
  2576. }
  2577. }
  2578. BundleMember = BundleMember->NextInBundle;
  2579. }
  2580. if (InsertInReadyList && SD->isReady()) {
  2581. ReadyInsts.push_back(SD);
  2582. DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n");
  2583. }
  2584. }
  2585. }
  2586. void BoUpSLP::BlockScheduling::resetSchedule() {
  2587. assert(ScheduleStart &&
  2588. "tried to reset schedule on block which has not been scheduled");
  2589. for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  2590. ScheduleData *SD = getScheduleData(I);
  2591. assert(isInSchedulingRegion(SD));
  2592. SD->IsScheduled = false;
  2593. SD->resetUnscheduledDeps();
  2594. }
  2595. ReadyInsts.clear();
  2596. }
  2597. void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
  2598. if (!BS->ScheduleStart)
  2599. return;
  2600. DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
  2601. BS->resetSchedule();
  2602. // For the real scheduling we use a more sophisticated ready-list: it is
  2603. // sorted by the original instruction location. This lets the final schedule
  2604. // be as close as possible to the original instruction order.
  2605. struct ScheduleDataCompare {
  2606. bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
  2607. return SD2->SchedulingPriority < SD1->SchedulingPriority;
  2608. }
  2609. };
  2610. std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
  2611. // Ensure that all depencency data is updated and fill the ready-list with
  2612. // initial instructions.
  2613. int Idx = 0;
  2614. int NumToSchedule = 0;
  2615. for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
  2616. I = I->getNextNode()) {
  2617. ScheduleData *SD = BS->getScheduleData(I);
  2618. assert(
  2619. SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
  2620. "scheduler and vectorizer have different opinion on what is a bundle");
  2621. SD->FirstInBundle->SchedulingPriority = Idx++;
  2622. if (SD->isSchedulingEntity()) {
  2623. BS->calculateDependencies(SD, false, this);
  2624. NumToSchedule++;
  2625. }
  2626. }
  2627. BS->initialFillReadyList(ReadyInsts);
  2628. Instruction *LastScheduledInst = BS->ScheduleEnd;
  2629. // Do the "real" scheduling.
  2630. while (!ReadyInsts.empty()) {
  2631. ScheduleData *picked = *ReadyInsts.begin();
  2632. ReadyInsts.erase(ReadyInsts.begin());
  2633. // Move the scheduled instruction(s) to their dedicated places, if not
  2634. // there yet.
  2635. ScheduleData *BundleMember = picked;
  2636. while (BundleMember) {
  2637. Instruction *pickedInst = BundleMember->Inst;
  2638. if (LastScheduledInst->getNextNode() != pickedInst) {
  2639. BS->BB->getInstList().remove(pickedInst);
  2640. BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
  2641. }
  2642. LastScheduledInst = pickedInst;
  2643. BundleMember = BundleMember->NextInBundle;
  2644. }
  2645. BS->schedule(picked, ReadyInsts);
  2646. NumToSchedule--;
  2647. }
  2648. assert(NumToSchedule == 0 && "could not schedule all instructions");
  2649. // Avoid duplicate scheduling of the block.
  2650. BS->ScheduleStart = nullptr;
  2651. }
  2652. /// The SLPVectorizer Pass.
  2653. struct SLPVectorizer : public FunctionPass {
  2654. typedef SmallVector<StoreInst *, 8> StoreList;
  2655. typedef MapVector<Value *, StoreList> StoreListMap;
  2656. /// Pass identification, replacement for typeid
  2657. static char ID;
  2658. explicit SLPVectorizer() : FunctionPass(ID) {
  2659. initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
  2660. }
  2661. ScalarEvolution *SE;
  2662. const DataLayout *DL;
  2663. TargetTransformInfo *TTI;
  2664. TargetLibraryInfo *TLI;
  2665. AliasAnalysis *AA;
  2666. LoopInfo *LI;
  2667. DominatorTree *DT;
  2668. AssumptionCache *AC;
  2669. bool runOnFunction(Function &F) override {
  2670. if (skipOptnoneFunction(F))
  2671. return false;
  2672. SE = &getAnalysis<ScalarEvolution>();
  2673. DL = &F.getParent()->getDataLayout();
  2674. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  2675. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  2676. TLI = TLIP ? &TLIP->getTLI() : nullptr;
  2677. AA = &getAnalysis<AliasAnalysis>();
  2678. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  2679. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  2680. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  2681. StoreRefs.clear();
  2682. bool Changed = false;
  2683. // If the target claims to have no vector registers don't attempt
  2684. // vectorization.
  2685. if (!TTI->getNumberOfRegisters(true))
  2686. return false;
  2687. // Must have DataLayout. We can't require it because some tests run w/o
  2688. // triple.
  2689. if (!DL)
  2690. return false;
  2691. // Don't vectorize when the attribute NoImplicitFloat is used.
  2692. if (F.hasFnAttribute(Attribute::NoImplicitFloat))
  2693. return false;
  2694. DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
  2695. // Use the bottom up slp vectorizer to construct chains that start with
  2696. // store instructions.
  2697. BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT, AC);
  2698. // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
  2699. // delete instructions.
  2700. // Scan the blocks in the function in post order.
  2701. for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
  2702. e = po_end(&F.getEntryBlock()); it != e; ++it) {
  2703. BasicBlock *BB = *it;
  2704. // Vectorize trees that end at stores.
  2705. if (unsigned count = collectStores(BB, R)) {
  2706. (void)count;
  2707. DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
  2708. Changed |= vectorizeStoreChains(R);
  2709. }
  2710. // Vectorize trees that end at reductions.
  2711. Changed |= vectorizeChainsInBlock(BB, R);
  2712. }
  2713. if (Changed) {
  2714. R.optimizeGatherSequence();
  2715. DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
  2716. DEBUG(verifyFunction(F));
  2717. }
  2718. return Changed;
  2719. }
  2720. void getAnalysisUsage(AnalysisUsage &AU) const override {
  2721. FunctionPass::getAnalysisUsage(AU);
  2722. AU.addRequired<AssumptionCacheTracker>();
  2723. AU.addRequired<ScalarEvolution>();
  2724. AU.addRequired<AliasAnalysis>();
  2725. AU.addRequired<TargetTransformInfoWrapperPass>();
  2726. AU.addRequired<LoopInfoWrapperPass>();
  2727. AU.addRequired<DominatorTreeWrapperPass>();
  2728. AU.addPreserved<LoopInfoWrapperPass>();
  2729. AU.addPreserved<DominatorTreeWrapperPass>();
  2730. AU.setPreservesCFG();
  2731. }
  2732. private:
  2733. /// \brief Collect memory references and sort them according to their base
  2734. /// object. We sort the stores to their base objects to reduce the cost of the
  2735. /// quadratic search on the stores. TODO: We can further reduce this cost
  2736. /// if we flush the chain creation every time we run into a memory barrier.
  2737. unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
  2738. /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
  2739. bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
  2740. /// \brief Try to vectorize a list of operands.
  2741. /// \@param BuildVector A list of users to ignore for the purpose of
  2742. /// scheduling and that don't need extracting.
  2743. /// \returns true if a value was vectorized.
  2744. bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
  2745. ArrayRef<Value *> BuildVector = None,
  2746. bool allowReorder = false);
  2747. /// \brief Try to vectorize a chain that may start at the operands of \V;
  2748. bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
  2749. /// \brief Vectorize the stores that were collected in StoreRefs.
  2750. bool vectorizeStoreChains(BoUpSLP &R);
  2751. /// \brief Scan the basic block and look for patterns that are likely to start
  2752. /// a vectorization chain.
  2753. bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
  2754. bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
  2755. BoUpSLP &R);
  2756. bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
  2757. BoUpSLP &R);
  2758. private:
  2759. StoreListMap StoreRefs;
  2760. };
  2761. /// \brief Check that the Values in the slice in VL array are still existent in
  2762. /// the WeakVH array.
  2763. /// Vectorization of part of the VL array may cause later values in the VL array
  2764. /// to become invalid. We track when this has happened in the WeakVH array.
  2765. static bool hasValueBeenRAUWed(ArrayRef<Value *> VL, ArrayRef<WeakVH> VH,
  2766. unsigned SliceBegin, unsigned SliceSize) {
  2767. VL = VL.slice(SliceBegin, SliceSize);
  2768. VH = VH.slice(SliceBegin, SliceSize);
  2769. return !std::equal(VL.begin(), VL.end(), VH.begin());
  2770. }
  2771. bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
  2772. int CostThreshold, BoUpSLP &R) {
  2773. unsigned ChainLen = Chain.size();
  2774. DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
  2775. << "\n");
  2776. Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
  2777. unsigned Sz = DL->getTypeSizeInBits(StoreTy);
  2778. unsigned VF = MinVecRegSize / Sz;
  2779. if (!isPowerOf2_32(Sz) || VF < 2)
  2780. return false;
  2781. // Keep track of values that were deleted by vectorizing in the loop below.
  2782. SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
  2783. bool Changed = false;
  2784. // Look for profitable vectorizable trees at all offsets, starting at zero.
  2785. for (unsigned i = 0, e = ChainLen; i < e; ++i) {
  2786. if (i + VF > e)
  2787. break;
  2788. // Check that a previous iteration of this loop did not delete the Value.
  2789. if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
  2790. continue;
  2791. DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
  2792. << "\n");
  2793. ArrayRef<Value *> Operands = Chain.slice(i, VF);
  2794. R.buildTree(Operands);
  2795. int Cost = R.getTreeCost();
  2796. DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
  2797. if (Cost < CostThreshold) {
  2798. DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
  2799. R.vectorizeTree();
  2800. // Move to the next bundle.
  2801. i += VF - 1;
  2802. Changed = true;
  2803. }
  2804. }
  2805. return Changed;
  2806. }
  2807. bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
  2808. int costThreshold, BoUpSLP &R) {
  2809. SetVector<Value *> Heads, Tails;
  2810. SmallDenseMap<Value *, Value *> ConsecutiveChain;
  2811. // We may run into multiple chains that merge into a single chain. We mark the
  2812. // stores that we vectorized so that we don't visit the same store twice.
  2813. BoUpSLP::ValueSet VectorizedStores;
  2814. bool Changed = false;
  2815. // Do a quadratic search on all of the given stores and find
  2816. // all of the pairs of stores that follow each other.
  2817. for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
  2818. for (unsigned j = 0; j < e; ++j) {
  2819. if (i == j)
  2820. continue;
  2821. if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
  2822. Tails.insert(Stores[j]);
  2823. Heads.insert(Stores[i]);
  2824. ConsecutiveChain[Stores[i]] = Stores[j];
  2825. }
  2826. }
  2827. }
  2828. // For stores that start but don't end a link in the chain:
  2829. for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
  2830. it != e; ++it) {
  2831. if (Tails.count(*it))
  2832. continue;
  2833. // We found a store instr that starts a chain. Now follow the chain and try
  2834. // to vectorize it.
  2835. BoUpSLP::ValueList Operands;
  2836. Value *I = *it;
  2837. // Collect the chain into a list.
  2838. while (Tails.count(I) || Heads.count(I)) {
  2839. if (VectorizedStores.count(I))
  2840. break;
  2841. Operands.push_back(I);
  2842. // Move to the next value in the chain.
  2843. I = ConsecutiveChain[I];
  2844. }
  2845. bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
  2846. // Mark the vectorized stores so that we don't vectorize them again.
  2847. if (Vectorized)
  2848. VectorizedStores.insert(Operands.begin(), Operands.end());
  2849. Changed |= Vectorized;
  2850. }
  2851. return Changed;
  2852. }
  2853. unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
  2854. unsigned count = 0;
  2855. StoreRefs.clear();
  2856. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  2857. StoreInst *SI = dyn_cast<StoreInst>(it);
  2858. if (!SI)
  2859. continue;
  2860. // Don't touch volatile stores.
  2861. if (!SI->isSimple())
  2862. continue;
  2863. // Check that the pointer points to scalars.
  2864. Type *Ty = SI->getValueOperand()->getType();
  2865. if (!isValidElementType(Ty))
  2866. continue;
  2867. // Find the base pointer.
  2868. Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
  2869. // Save the store locations.
  2870. StoreRefs[Ptr].push_back(SI);
  2871. count++;
  2872. }
  2873. return count;
  2874. }
  2875. bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
  2876. if (!A || !B)
  2877. return false;
  2878. Value *VL[] = { A, B };
  2879. return tryToVectorizeList(VL, R, None, true);
  2880. }
  2881. bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
  2882. ArrayRef<Value *> BuildVector,
  2883. bool allowReorder) {
  2884. if (VL.size() < 2)
  2885. return false;
  2886. DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
  2887. // Check that all of the parts are scalar instructions of the same type.
  2888. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  2889. if (!I0)
  2890. return false;
  2891. unsigned Opcode0 = I0->getOpcode();
  2892. Type *Ty0 = I0->getType();
  2893. unsigned Sz = DL->getTypeSizeInBits(Ty0);
  2894. unsigned VF = MinVecRegSize / Sz;
  2895. for (int i = 0, e = VL.size(); i < e; ++i) {
  2896. Type *Ty = VL[i]->getType();
  2897. if (!isValidElementType(Ty))
  2898. return false;
  2899. Instruction *Inst = dyn_cast<Instruction>(VL[i]);
  2900. if (!Inst || Inst->getOpcode() != Opcode0)
  2901. return false;
  2902. }
  2903. bool Changed = false;
  2904. // Keep track of values that were deleted by vectorizing in the loop below.
  2905. SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
  2906. for (unsigned i = 0, e = VL.size(); i < e; ++i) {
  2907. unsigned OpsWidth = 0;
  2908. if (i + VF > e)
  2909. OpsWidth = e - i;
  2910. else
  2911. OpsWidth = VF;
  2912. if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
  2913. break;
  2914. // Check that a previous iteration of this loop did not delete the Value.
  2915. if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
  2916. continue;
  2917. DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
  2918. << "\n");
  2919. ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
  2920. ArrayRef<Value *> BuildVectorSlice;
  2921. if (!BuildVector.empty())
  2922. BuildVectorSlice = BuildVector.slice(i, OpsWidth);
  2923. R.buildTree(Ops, BuildVectorSlice);
  2924. // TODO: check if we can allow reordering also for other cases than
  2925. // tryToVectorizePair()
  2926. if (allowReorder && R.shouldReorder()) {
  2927. assert(Ops.size() == 2);
  2928. assert(BuildVectorSlice.empty());
  2929. Value *ReorderedOps[] = { Ops[1], Ops[0] };
  2930. R.buildTree(ReorderedOps, None);
  2931. }
  2932. int Cost = R.getTreeCost();
  2933. if (Cost < -SLPCostThreshold) {
  2934. DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
  2935. Value *VectorizedRoot = R.vectorizeTree();
  2936. // Reconstruct the build vector by extracting the vectorized root. This
  2937. // way we handle the case where some elements of the vector are undefined.
  2938. // (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
  2939. if (!BuildVectorSlice.empty()) {
  2940. // The insert point is the last build vector instruction. The vectorized
  2941. // root will precede it. This guarantees that we get an instruction. The
  2942. // vectorized tree could have been constant folded.
  2943. Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
  2944. unsigned VecIdx = 0;
  2945. for (auto &V : BuildVectorSlice) {
  2946. IRBuilder<true, NoFolder> Builder(
  2947. ++BasicBlock::iterator(InsertAfter));
  2948. InsertElementInst *IE = cast<InsertElementInst>(V);
  2949. Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
  2950. VectorizedRoot, Builder.getInt32(VecIdx++)));
  2951. IE->setOperand(1, Extract);
  2952. IE->removeFromParent();
  2953. IE->insertAfter(Extract);
  2954. InsertAfter = IE;
  2955. }
  2956. }
  2957. // Move to the next bundle.
  2958. i += VF - 1;
  2959. Changed = true;
  2960. }
  2961. }
  2962. return Changed;
  2963. }
  2964. bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
  2965. if (!V)
  2966. return false;
  2967. // Try to vectorize V.
  2968. if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
  2969. return true;
  2970. BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
  2971. BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
  2972. // Try to skip B.
  2973. if (B && B->hasOneUse()) {
  2974. BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
  2975. BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
  2976. if (tryToVectorizePair(A, B0, R)) {
  2977. return true;
  2978. }
  2979. if (tryToVectorizePair(A, B1, R)) {
  2980. return true;
  2981. }
  2982. }
  2983. // Try to skip A.
  2984. if (A && A->hasOneUse()) {
  2985. BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
  2986. BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
  2987. if (tryToVectorizePair(A0, B, R)) {
  2988. return true;
  2989. }
  2990. if (tryToVectorizePair(A1, B, R)) {
  2991. return true;
  2992. }
  2993. }
  2994. return 0;
  2995. }
  2996. /// \brief Generate a shuffle mask to be used in a reduction tree.
  2997. ///
  2998. /// \param VecLen The length of the vector to be reduced.
  2999. /// \param NumEltsToRdx The number of elements that should be reduced in the
  3000. /// vector.
  3001. /// \param IsPairwise Whether the reduction is a pairwise or splitting
  3002. /// reduction. A pairwise reduction will generate a mask of
  3003. /// <0,2,...> or <1,3,..> while a splitting reduction will generate
  3004. /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
  3005. /// \param IsLeft True will generate a mask of even elements, odd otherwise.
  3006. static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
  3007. bool IsPairwise, bool IsLeft,
  3008. IRBuilder<> &Builder) {
  3009. assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
  3010. SmallVector<Constant *, 32> ShuffleMask(
  3011. VecLen, UndefValue::get(Builder.getInt32Ty()));
  3012. if (IsPairwise)
  3013. // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
  3014. for (unsigned i = 0; i != NumEltsToRdx; ++i)
  3015. ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
  3016. else
  3017. // Move the upper half of the vector to the lower half.
  3018. for (unsigned i = 0; i != NumEltsToRdx; ++i)
  3019. ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
  3020. return ConstantVector::get(ShuffleMask);
  3021. }
  3022. /// Model horizontal reductions.
  3023. ///
  3024. /// A horizontal reduction is a tree of reduction operations (currently add and
  3025. /// fadd) that has operations that can be put into a vector as its leaf.
  3026. /// For example, this tree:
  3027. ///
  3028. /// mul mul mul mul
  3029. /// \ / \ /
  3030. /// + +
  3031. /// \ /
  3032. /// +
  3033. /// This tree has "mul" as its reduced values and "+" as its reduction
  3034. /// operations. A reduction might be feeding into a store or a binary operation
  3035. /// feeding a phi.
  3036. /// ...
  3037. /// \ /
  3038. /// +
  3039. /// |
  3040. /// phi +=
  3041. ///
  3042. /// Or:
  3043. /// ...
  3044. /// \ /
  3045. /// +
  3046. /// |
  3047. /// *p =
  3048. ///
  3049. class HorizontalReduction {
  3050. SmallVector<Value *, 16> ReductionOps;
  3051. SmallVector<Value *, 32> ReducedVals;
  3052. BinaryOperator *ReductionRoot;
  3053. PHINode *ReductionPHI;
  3054. /// The opcode of the reduction.
  3055. unsigned ReductionOpcode;
  3056. /// The opcode of the values we perform a reduction on.
  3057. unsigned ReducedValueOpcode;
  3058. /// The width of one full horizontal reduction operation.
  3059. unsigned ReduxWidth;
  3060. /// Should we model this reduction as a pairwise reduction tree or a tree that
  3061. /// splits the vector in halves and adds those halves.
  3062. bool IsPairwiseReduction;
  3063. public:
  3064. HorizontalReduction()
  3065. : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
  3066. ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
  3067. /// \brief Try to find a reduction tree.
  3068. bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
  3069. const DataLayout *DL) {
  3070. assert((!Phi ||
  3071. std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
  3072. "Thi phi needs to use the binary operator");
  3073. // We could have a initial reductions that is not an add.
  3074. // r *= v1 + v2 + v3 + v4
  3075. // In such a case start looking for a tree rooted in the first '+'.
  3076. if (Phi) {
  3077. if (B->getOperand(0) == Phi) {
  3078. Phi = nullptr;
  3079. B = dyn_cast<BinaryOperator>(B->getOperand(1));
  3080. } else if (B->getOperand(1) == Phi) {
  3081. Phi = nullptr;
  3082. B = dyn_cast<BinaryOperator>(B->getOperand(0));
  3083. }
  3084. }
  3085. if (!B)
  3086. return false;
  3087. Type *Ty = B->getType();
  3088. if (!isValidElementType(Ty))
  3089. return false;
  3090. ReductionOpcode = B->getOpcode();
  3091. ReducedValueOpcode = 0;
  3092. ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
  3093. ReductionRoot = B;
  3094. ReductionPHI = Phi;
  3095. if (ReduxWidth < 4)
  3096. return false;
  3097. // We currently only support adds.
  3098. if (ReductionOpcode != Instruction::Add &&
  3099. ReductionOpcode != Instruction::FAdd)
  3100. return false;
  3101. // Post order traverse the reduction tree starting at B. We only handle true
  3102. // trees containing only binary operators.
  3103. SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
  3104. Stack.push_back(std::make_pair(B, 0));
  3105. while (!Stack.empty()) {
  3106. BinaryOperator *TreeN = Stack.back().first;
  3107. unsigned EdgeToVist = Stack.back().second++;
  3108. bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
  3109. // Only handle trees in the current basic block.
  3110. if (TreeN->getParent() != B->getParent())
  3111. return false;
  3112. // Each tree node needs to have one user except for the ultimate
  3113. // reduction.
  3114. if (!TreeN->hasOneUse() && TreeN != B)
  3115. return false;
  3116. // Postorder vist.
  3117. if (EdgeToVist == 2 || IsReducedValue) {
  3118. if (IsReducedValue) {
  3119. // Make sure that the opcodes of the operations that we are going to
  3120. // reduce match.
  3121. if (!ReducedValueOpcode)
  3122. ReducedValueOpcode = TreeN->getOpcode();
  3123. else if (ReducedValueOpcode != TreeN->getOpcode())
  3124. return false;
  3125. ReducedVals.push_back(TreeN);
  3126. } else {
  3127. // We need to be able to reassociate the adds.
  3128. if (!TreeN->isAssociative())
  3129. return false;
  3130. ReductionOps.push_back(TreeN);
  3131. }
  3132. // Retract.
  3133. Stack.pop_back();
  3134. continue;
  3135. }
  3136. // Visit left or right.
  3137. Value *NextV = TreeN->getOperand(EdgeToVist);
  3138. BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
  3139. if (Next)
  3140. Stack.push_back(std::make_pair(Next, 0));
  3141. else if (NextV != Phi)
  3142. return false;
  3143. }
  3144. return true;
  3145. }
  3146. /// \brief Attempt to vectorize the tree found by
  3147. /// matchAssociativeReduction.
  3148. bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
  3149. if (ReducedVals.empty())
  3150. return false;
  3151. unsigned NumReducedVals = ReducedVals.size();
  3152. if (NumReducedVals < ReduxWidth)
  3153. return false;
  3154. Value *VectorizedTree = nullptr;
  3155. IRBuilder<> Builder(ReductionRoot);
  3156. FastMathFlags Unsafe;
  3157. Unsafe.setUnsafeAlgebra();
  3158. Builder.SetFastMathFlags(Unsafe);
  3159. unsigned i = 0;
  3160. for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
  3161. V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
  3162. // Estimate cost.
  3163. int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
  3164. if (Cost >= -SLPCostThreshold)
  3165. break;
  3166. DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
  3167. << ". (HorRdx)\n");
  3168. // Vectorize a tree.
  3169. DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
  3170. Value *VectorizedRoot = V.vectorizeTree();
  3171. // Emit a reduction.
  3172. Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
  3173. if (VectorizedTree) {
  3174. Builder.SetCurrentDebugLocation(Loc);
  3175. VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
  3176. ReducedSubTree, "bin.rdx");
  3177. } else
  3178. VectorizedTree = ReducedSubTree;
  3179. }
  3180. if (VectorizedTree) {
  3181. // Finish the reduction.
  3182. for (; i < NumReducedVals; ++i) {
  3183. Builder.SetCurrentDebugLocation(
  3184. cast<Instruction>(ReducedVals[i])->getDebugLoc());
  3185. VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
  3186. ReducedVals[i]);
  3187. }
  3188. // Update users.
  3189. if (ReductionPHI) {
  3190. assert(ReductionRoot && "Need a reduction operation");
  3191. ReductionRoot->setOperand(0, VectorizedTree);
  3192. ReductionRoot->setOperand(1, ReductionPHI);
  3193. } else
  3194. ReductionRoot->replaceAllUsesWith(VectorizedTree);
  3195. }
  3196. return VectorizedTree != nullptr;
  3197. }
  3198. private:
  3199. /// \brief Calcuate the cost of a reduction.
  3200. int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
  3201. Type *ScalarTy = FirstReducedVal->getType();
  3202. Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
  3203. int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
  3204. int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
  3205. IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
  3206. int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
  3207. int ScalarReduxCost =
  3208. ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
  3209. DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
  3210. << " for reduction that starts with " << *FirstReducedVal
  3211. << " (It is a "
  3212. << (IsPairwiseReduction ? "pairwise" : "splitting")
  3213. << " reduction)\n");
  3214. return VecReduxCost - ScalarReduxCost;
  3215. }
  3216. static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
  3217. Value *R, const Twine &Name = "") {
  3218. if (Opcode == Instruction::FAdd)
  3219. return Builder.CreateFAdd(L, R, Name);
  3220. return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
  3221. }
  3222. /// \brief Emit a horizontal reduction of the vectorized value.
  3223. Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
  3224. assert(VectorizedValue && "Need to have a vectorized tree node");
  3225. assert(isPowerOf2_32(ReduxWidth) &&
  3226. "We only handle power-of-two reductions for now");
  3227. Value *TmpVec = VectorizedValue;
  3228. for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
  3229. if (IsPairwiseReduction) {
  3230. Value *LeftMask =
  3231. createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
  3232. Value *RightMask =
  3233. createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
  3234. Value *LeftShuf = Builder.CreateShuffleVector(
  3235. TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
  3236. Value *RightShuf = Builder.CreateShuffleVector(
  3237. TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
  3238. "rdx.shuf.r");
  3239. TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
  3240. "bin.rdx");
  3241. } else {
  3242. Value *UpperHalf =
  3243. createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
  3244. Value *Shuf = Builder.CreateShuffleVector(
  3245. TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
  3246. TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
  3247. }
  3248. }
  3249. // The result is in the first element of the vector.
  3250. return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
  3251. }
  3252. };
  3253. /// \brief Recognize construction of vectors like
  3254. /// %ra = insertelement <4 x float> undef, float %s0, i32 0
  3255. /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
  3256. /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
  3257. /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
  3258. ///
  3259. /// Returns true if it matches
  3260. ///
  3261. static bool findBuildVector(InsertElementInst *FirstInsertElem,
  3262. SmallVectorImpl<Value *> &BuildVector,
  3263. SmallVectorImpl<Value *> &BuildVectorOpds) {
  3264. if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
  3265. return false;
  3266. InsertElementInst *IE = FirstInsertElem;
  3267. while (true) {
  3268. BuildVector.push_back(IE);
  3269. BuildVectorOpds.push_back(IE->getOperand(1));
  3270. if (IE->use_empty())
  3271. return false;
  3272. InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
  3273. if (!NextUse)
  3274. return true;
  3275. // If this isn't the final use, make sure the next insertelement is the only
  3276. // use. It's OK if the final constructed vector is used multiple times
  3277. if (!IE->hasOneUse())
  3278. return false;
  3279. IE = NextUse;
  3280. }
  3281. return false;
  3282. }
  3283. static bool PhiTypeSorterFunc(Value *V, Value *V2) {
  3284. return V->getType() < V2->getType();
  3285. }
  3286. bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
  3287. bool Changed = false;
  3288. SmallVector<Value *, 4> Incoming;
  3289. SmallSet<Value *, 16> VisitedInstrs;
  3290. bool HaveVectorizedPhiNodes = true;
  3291. while (HaveVectorizedPhiNodes) {
  3292. HaveVectorizedPhiNodes = false;
  3293. // Collect the incoming values from the PHIs.
  3294. Incoming.clear();
  3295. for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
  3296. ++instr) {
  3297. PHINode *P = dyn_cast<PHINode>(instr);
  3298. if (!P)
  3299. break;
  3300. if (!VisitedInstrs.count(P))
  3301. Incoming.push_back(P);
  3302. }
  3303. // Sort by type.
  3304. std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
  3305. // Try to vectorize elements base on their type.
  3306. for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
  3307. E = Incoming.end();
  3308. IncIt != E;) {
  3309. // Look for the next elements with the same type.
  3310. SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
  3311. while (SameTypeIt != E &&
  3312. (*SameTypeIt)->getType() == (*IncIt)->getType()) {
  3313. VisitedInstrs.insert(*SameTypeIt);
  3314. ++SameTypeIt;
  3315. }
  3316. // Try to vectorize them.
  3317. unsigned NumElts = (SameTypeIt - IncIt);
  3318. DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
  3319. if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
  3320. // Success start over because instructions might have been changed.
  3321. HaveVectorizedPhiNodes = true;
  3322. Changed = true;
  3323. break;
  3324. }
  3325. // Start over at the next instruction of a different type (or the end).
  3326. IncIt = SameTypeIt;
  3327. }
  3328. }
  3329. VisitedInstrs.clear();
  3330. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
  3331. // We may go through BB multiple times so skip the one we have checked.
  3332. if (!VisitedInstrs.insert(it).second)
  3333. continue;
  3334. if (isa<DbgInfoIntrinsic>(it))
  3335. continue;
  3336. // Try to vectorize reductions that use PHINodes.
  3337. if (PHINode *P = dyn_cast<PHINode>(it)) {
  3338. // Check that the PHI is a reduction PHI.
  3339. if (P->getNumIncomingValues() != 2)
  3340. return Changed;
  3341. Value *Rdx =
  3342. (P->getIncomingBlock(0) == BB
  3343. ? (P->getIncomingValue(0))
  3344. : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
  3345. : nullptr));
  3346. // Check if this is a Binary Operator.
  3347. BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
  3348. if (!BI)
  3349. continue;
  3350. // Try to match and vectorize a horizontal reduction.
  3351. HorizontalReduction HorRdx;
  3352. if (ShouldVectorizeHor &&
  3353. HorRdx.matchAssociativeReduction(P, BI, DL) &&
  3354. HorRdx.tryToReduce(R, TTI)) {
  3355. Changed = true;
  3356. it = BB->begin();
  3357. e = BB->end();
  3358. continue;
  3359. }
  3360. Value *Inst = BI->getOperand(0);
  3361. if (Inst == P)
  3362. Inst = BI->getOperand(1);
  3363. if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
  3364. // We would like to start over since some instructions are deleted
  3365. // and the iterator may become invalid value.
  3366. Changed = true;
  3367. it = BB->begin();
  3368. e = BB->end();
  3369. continue;
  3370. }
  3371. continue;
  3372. }
  3373. // Try to vectorize horizontal reductions feeding into a store.
  3374. if (ShouldStartVectorizeHorAtStore)
  3375. if (StoreInst *SI = dyn_cast<StoreInst>(it))
  3376. if (BinaryOperator *BinOp =
  3377. dyn_cast<BinaryOperator>(SI->getValueOperand())) {
  3378. HorizontalReduction HorRdx;
  3379. if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
  3380. HorRdx.tryToReduce(R, TTI)) ||
  3381. tryToVectorize(BinOp, R))) {
  3382. Changed = true;
  3383. it = BB->begin();
  3384. e = BB->end();
  3385. continue;
  3386. }
  3387. }
  3388. // Try to vectorize horizontal reductions feeding into a return.
  3389. if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
  3390. if (RI->getNumOperands() != 0)
  3391. if (BinaryOperator *BinOp =
  3392. dyn_cast<BinaryOperator>(RI->getOperand(0))) {
  3393. DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
  3394. if (tryToVectorizePair(BinOp->getOperand(0),
  3395. BinOp->getOperand(1), R)) {
  3396. Changed = true;
  3397. it = BB->begin();
  3398. e = BB->end();
  3399. continue;
  3400. }
  3401. }
  3402. // Try to vectorize trees that start at compare instructions.
  3403. if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
  3404. if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
  3405. Changed = true;
  3406. // We would like to start over since some instructions are deleted
  3407. // and the iterator may become invalid value.
  3408. it = BB->begin();
  3409. e = BB->end();
  3410. continue;
  3411. }
  3412. for (int i = 0; i < 2; ++i) {
  3413. if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
  3414. if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
  3415. Changed = true;
  3416. // We would like to start over since some instructions are deleted
  3417. // and the iterator may become invalid value.
  3418. it = BB->begin();
  3419. e = BB->end();
  3420. break;
  3421. }
  3422. }
  3423. }
  3424. continue;
  3425. }
  3426. // Try to vectorize trees that start at insertelement instructions.
  3427. if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
  3428. SmallVector<Value *, 16> BuildVector;
  3429. SmallVector<Value *, 16> BuildVectorOpds;
  3430. if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
  3431. continue;
  3432. // Vectorize starting with the build vector operands ignoring the
  3433. // BuildVector instructions for the purpose of scheduling and user
  3434. // extraction.
  3435. if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
  3436. Changed = true;
  3437. it = BB->begin();
  3438. e = BB->end();
  3439. }
  3440. continue;
  3441. }
  3442. }
  3443. return Changed;
  3444. }
  3445. bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
  3446. bool Changed = false;
  3447. // Attempt to sort and vectorize each of the store-groups.
  3448. for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
  3449. it != e; ++it) {
  3450. if (it->second.size() < 2)
  3451. continue;
  3452. DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
  3453. << it->second.size() << ".\n");
  3454. // Process the stores in chunks of 16.
  3455. for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
  3456. unsigned Len = std::min<unsigned>(CE - CI, 16);
  3457. Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
  3458. -SLPCostThreshold, R);
  3459. }
  3460. }
  3461. return Changed;
  3462. }
  3463. } // end anonymous namespace
  3464. char SLPVectorizer::ID = 0;
  3465. static const char lv_name[] = "SLP Vectorizer";
  3466. INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
  3467. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  3468. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  3469. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  3470. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  3471. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  3472. INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
  3473. namespace llvm {
  3474. Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
  3475. }