MachinePipeliner.cpp 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212
  1. //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
  11. //
  12. // Software pipelining (SWP) is an instruction scheduling technique for loops
  13. // that overlap loop iterations and exploits ILP via a compiler transformation.
  14. //
  15. // Swing Modulo Scheduling is an implementation of software pipelining
  16. // that generates schedules that are near optimal in terms of initiation
  17. // interval, register requirements, and stage count. See the papers:
  18. //
  19. // "Swing Modulo Scheduling: A Lifetime-Sensitive Approach", by J. Llosa,
  20. // A. Gonzalez, E. Ayguade, and M. Valero. In PACT '96 Processings of the 1996
  21. // Conference on Parallel Architectures and Compilation Techiniques.
  22. //
  23. // "Lifetime-Sensitive Modulo Scheduling in a Production Environment", by J.
  24. // Llosa, E. Ayguade, A. Gonzalez, M. Valero, and J. Eckhardt. In IEEE
  25. // Transactions on Computers, Vol. 50, No. 3, 2001.
  26. //
  27. // "An Implementation of Swing Modulo Scheduling With Extensions for
  28. // Superblocks", by T. Lattner, Master's Thesis, University of Illinois at
  29. // Urbana-Chambpain, 2005.
  30. //
  31. //
  32. // The SMS algorithm consists of three main steps after computing the minimal
  33. // initiation interval (MII).
  34. // 1) Analyze the dependence graph and compute information about each
  35. // instruction in the graph.
  36. // 2) Order the nodes (instructions) by priority based upon the heuristics
  37. // described in the algorithm.
  38. // 3) Attempt to schedule the nodes in the specified order using the MII.
  39. //
  40. // This SMS implementation is a target-independent back-end pass. When enabled,
  41. // the pass runs just prior to the register allocation pass, while the machine
  42. // IR is in SSA form. If software pipelining is successful, then the original
  43. // loop is replaced by the optimized loop. The optimized loop contains one or
  44. // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
  45. // the instructions cannot be scheduled in a given MII, we increase the MII by
  46. // one and try again.
  47. //
  48. // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
  49. // represent loop carried dependences in the DAG as order edges to the Phi
  50. // nodes. We also perform several passes over the DAG to eliminate unnecessary
  51. // edges that inhibit the ability to pipeline. The implementation uses the
  52. // DFAPacketizer class to compute the minimum initiation interval and the check
  53. // where an instruction may be inserted in the pipelined schedule.
  54. //
  55. // In order for the SMS pass to work, several target specific hooks need to be
  56. // implemented to get information about the loop structure and to rewrite
  57. // instructions.
  58. //
  59. //===----------------------------------------------------------------------===//
  60. #include "llvm/ADT/ArrayRef.h"
  61. #include "llvm/ADT/BitVector.h"
  62. #include "llvm/ADT/DenseMap.h"
  63. #include "llvm/ADT/MapVector.h"
  64. #include "llvm/ADT/PriorityQueue.h"
  65. #include "llvm/ADT/SetVector.h"
  66. #include "llvm/ADT/SmallPtrSet.h"
  67. #include "llvm/ADT/SmallSet.h"
  68. #include "llvm/ADT/SmallVector.h"
  69. #include "llvm/ADT/Statistic.h"
  70. #include "llvm/ADT/iterator_range.h"
  71. #include "llvm/Analysis/AliasAnalysis.h"
  72. #include "llvm/Analysis/MemoryLocation.h"
  73. #include "llvm/Analysis/ValueTracking.h"
  74. #include "llvm/CodeGen/DFAPacketizer.h"
  75. #include "llvm/CodeGen/LiveIntervals.h"
  76. #include "llvm/CodeGen/MachineBasicBlock.h"
  77. #include "llvm/CodeGen/MachineDominators.h"
  78. #include "llvm/CodeGen/MachineFunction.h"
  79. #include "llvm/CodeGen/MachineFunctionPass.h"
  80. #include "llvm/CodeGen/MachineInstr.h"
  81. #include "llvm/CodeGen/MachineInstrBuilder.h"
  82. #include "llvm/CodeGen/MachineLoopInfo.h"
  83. #include "llvm/CodeGen/MachineMemOperand.h"
  84. #include "llvm/CodeGen/MachineOperand.h"
  85. #include "llvm/CodeGen/MachineRegisterInfo.h"
  86. #include "llvm/CodeGen/RegisterClassInfo.h"
  87. #include "llvm/CodeGen/RegisterPressure.h"
  88. #include "llvm/CodeGen/ScheduleDAG.h"
  89. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  90. #include "llvm/CodeGen/ScheduleDAGMutation.h"
  91. #include "llvm/CodeGen/TargetInstrInfo.h"
  92. #include "llvm/CodeGen/TargetOpcodes.h"
  93. #include "llvm/CodeGen/TargetRegisterInfo.h"
  94. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  95. #include "llvm/Config/llvm-config.h"
  96. #include "llvm/IR/Attributes.h"
  97. #include "llvm/IR/DebugLoc.h"
  98. #include "llvm/IR/Function.h"
  99. #include "llvm/MC/LaneBitmask.h"
  100. #include "llvm/MC/MCInstrDesc.h"
  101. #include "llvm/MC/MCInstrItineraries.h"
  102. #include "llvm/MC/MCRegisterInfo.h"
  103. #include "llvm/Pass.h"
  104. #include "llvm/Support/CommandLine.h"
  105. #include "llvm/Support/Compiler.h"
  106. #include "llvm/Support/Debug.h"
  107. #include "llvm/Support/MathExtras.h"
  108. #include "llvm/Support/raw_ostream.h"
  109. #include <algorithm>
  110. #include <cassert>
  111. #include <climits>
  112. #include <cstdint>
  113. #include <deque>
  114. #include <functional>
  115. #include <iterator>
  116. #include <map>
  117. #include <memory>
  118. #include <tuple>
  119. #include <utility>
  120. #include <vector>
  121. using namespace llvm;
  122. #define DEBUG_TYPE "pipeliner"
  123. STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
  124. STATISTIC(NumPipelined, "Number of loops software pipelined");
  125. STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
  126. /// A command line option to turn software pipelining on or off.
  127. static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
  128. cl::ZeroOrMore,
  129. cl::desc("Enable Software Pipelining"));
  130. /// A command line option to enable SWP at -Os.
  131. static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
  132. cl::desc("Enable SWP at Os."), cl::Hidden,
  133. cl::init(false));
  134. /// A command line argument to limit minimum initial interval for pipelining.
  135. static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
  136. cl::desc("Size limit for the MII."),
  137. cl::Hidden, cl::init(27));
  138. /// A command line argument to limit the number of stages in the pipeline.
  139. static cl::opt<int>
  140. SwpMaxStages("pipeliner-max-stages",
  141. cl::desc("Maximum stages allowed in the generated scheduled."),
  142. cl::Hidden, cl::init(3));
  143. /// A command line option to disable the pruning of chain dependences due to
  144. /// an unrelated Phi.
  145. static cl::opt<bool>
  146. SwpPruneDeps("pipeliner-prune-deps",
  147. cl::desc("Prune dependences between unrelated Phi nodes."),
  148. cl::Hidden, cl::init(true));
  149. /// A command line option to disable the pruning of loop carried order
  150. /// dependences.
  151. static cl::opt<bool>
  152. SwpPruneLoopCarried("pipeliner-prune-loop-carried",
  153. cl::desc("Prune loop carried order dependences."),
  154. cl::Hidden, cl::init(true));
  155. #ifndef NDEBUG
  156. static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
  157. #endif
  158. static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
  159. cl::ReallyHidden, cl::init(false),
  160. cl::ZeroOrMore, cl::desc("Ignore RecMII"));
  161. namespace {
  162. class NodeSet;
  163. class SMSchedule;
  164. /// The main class in the implementation of the target independent
  165. /// software pipeliner pass.
  166. class MachinePipeliner : public MachineFunctionPass {
  167. public:
  168. MachineFunction *MF = nullptr;
  169. const MachineLoopInfo *MLI = nullptr;
  170. const MachineDominatorTree *MDT = nullptr;
  171. const InstrItineraryData *InstrItins;
  172. const TargetInstrInfo *TII = nullptr;
  173. RegisterClassInfo RegClassInfo;
  174. #ifndef NDEBUG
  175. static int NumTries;
  176. #endif
  177. /// Cache the target analysis information about the loop.
  178. struct LoopInfo {
  179. MachineBasicBlock *TBB = nullptr;
  180. MachineBasicBlock *FBB = nullptr;
  181. SmallVector<MachineOperand, 4> BrCond;
  182. MachineInstr *LoopInductionVar = nullptr;
  183. MachineInstr *LoopCompare = nullptr;
  184. };
  185. LoopInfo LI;
  186. static char ID;
  187. MachinePipeliner() : MachineFunctionPass(ID) {
  188. initializeMachinePipelinerPass(*PassRegistry::getPassRegistry());
  189. }
  190. bool runOnMachineFunction(MachineFunction &MF) override;
  191. void getAnalysisUsage(AnalysisUsage &AU) const override {
  192. AU.addRequired<AAResultsWrapperPass>();
  193. AU.addPreserved<AAResultsWrapperPass>();
  194. AU.addRequired<MachineLoopInfo>();
  195. AU.addRequired<MachineDominatorTree>();
  196. AU.addRequired<LiveIntervals>();
  197. MachineFunctionPass::getAnalysisUsage(AU);
  198. }
  199. private:
  200. void preprocessPhiNodes(MachineBasicBlock &B);
  201. bool canPipelineLoop(MachineLoop &L);
  202. bool scheduleLoop(MachineLoop &L);
  203. bool swingModuloScheduler(MachineLoop &L);
  204. };
  205. /// This class builds the dependence graph for the instructions in a loop,
  206. /// and attempts to schedule the instructions using the SMS algorithm.
  207. class SwingSchedulerDAG : public ScheduleDAGInstrs {
  208. MachinePipeliner &Pass;
  209. /// The minimum initiation interval between iterations for this schedule.
  210. unsigned MII = 0;
  211. /// Set to true if a valid pipelined schedule is found for the loop.
  212. bool Scheduled = false;
  213. MachineLoop &Loop;
  214. LiveIntervals &LIS;
  215. const RegisterClassInfo &RegClassInfo;
  216. /// A toplogical ordering of the SUnits, which is needed for changing
  217. /// dependences and iterating over the SUnits.
  218. ScheduleDAGTopologicalSort Topo;
  219. struct NodeInfo {
  220. int ASAP = 0;
  221. int ALAP = 0;
  222. int ZeroLatencyDepth = 0;
  223. int ZeroLatencyHeight = 0;
  224. NodeInfo() = default;
  225. };
  226. /// Computed properties for each node in the graph.
  227. std::vector<NodeInfo> ScheduleInfo;
  228. enum OrderKind { BottomUp = 0, TopDown = 1 };
  229. /// Computed node ordering for scheduling.
  230. SetVector<SUnit *> NodeOrder;
  231. using NodeSetType = SmallVector<NodeSet, 8>;
  232. using ValueMapTy = DenseMap<unsigned, unsigned>;
  233. using MBBVectorTy = SmallVectorImpl<MachineBasicBlock *>;
  234. using InstrMapTy = DenseMap<MachineInstr *, MachineInstr *>;
  235. /// Instructions to change when emitting the final schedule.
  236. DenseMap<SUnit *, std::pair<unsigned, int64_t>> InstrChanges;
  237. /// We may create a new instruction, so remember it because it
  238. /// must be deleted when the pass is finished.
  239. SmallPtrSet<MachineInstr *, 4> NewMIs;
  240. /// Ordered list of DAG postprocessing steps.
  241. std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
  242. /// Helper class to implement Johnson's circuit finding algorithm.
  243. class Circuits {
  244. std::vector<SUnit> &SUnits;
  245. SetVector<SUnit *> Stack;
  246. BitVector Blocked;
  247. SmallVector<SmallPtrSet<SUnit *, 4>, 10> B;
  248. SmallVector<SmallVector<int, 4>, 16> AdjK;
  249. unsigned NumPaths;
  250. static unsigned MaxPaths;
  251. public:
  252. Circuits(std::vector<SUnit> &SUs)
  253. : SUnits(SUs), Blocked(SUs.size()), B(SUs.size()), AdjK(SUs.size()) {}
  254. /// Reset the data structures used in the circuit algorithm.
  255. void reset() {
  256. Stack.clear();
  257. Blocked.reset();
  258. B.assign(SUnits.size(), SmallPtrSet<SUnit *, 4>());
  259. NumPaths = 0;
  260. }
  261. void createAdjacencyStructure(SwingSchedulerDAG *DAG);
  262. bool circuit(int V, int S, NodeSetType &NodeSets, bool HasBackedge = false);
  263. void unblock(int U);
  264. };
  265. public:
  266. SwingSchedulerDAG(MachinePipeliner &P, MachineLoop &L, LiveIntervals &lis,
  267. const RegisterClassInfo &rci)
  268. : ScheduleDAGInstrs(*P.MF, P.MLI, false), Pass(P), Loop(L), LIS(lis),
  269. RegClassInfo(rci), Topo(SUnits, &ExitSU) {
  270. P.MF->getSubtarget().getSMSMutations(Mutations);
  271. }
  272. void schedule() override;
  273. void finishBlock() override;
  274. /// Return true if the loop kernel has been scheduled.
  275. bool hasNewSchedule() { return Scheduled; }
  276. /// Return the earliest time an instruction may be scheduled.
  277. int getASAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ASAP; }
  278. /// Return the latest time an instruction my be scheduled.
  279. int getALAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ALAP; }
  280. /// The mobility function, which the number of slots in which
  281. /// an instruction may be scheduled.
  282. int getMOV(SUnit *Node) { return getALAP(Node) - getASAP(Node); }
  283. /// The depth, in the dependence graph, for a node.
  284. unsigned getDepth(SUnit *Node) { return Node->getDepth(); }
  285. /// The maximum unweighted length of a path from an arbitrary node to the
  286. /// given node in which each edge has latency 0
  287. int getZeroLatencyDepth(SUnit *Node) {
  288. return ScheduleInfo[Node->NodeNum].ZeroLatencyDepth;
  289. }
  290. /// The height, in the dependence graph, for a node.
  291. unsigned getHeight(SUnit *Node) { return Node->getHeight(); }
  292. /// The maximum unweighted length of a path from the given node to an
  293. /// arbitrary node in which each edge has latency 0
  294. int getZeroLatencyHeight(SUnit *Node) {
  295. return ScheduleInfo[Node->NodeNum].ZeroLatencyHeight;
  296. }
  297. /// Return true if the dependence is a back-edge in the data dependence graph.
  298. /// Since the DAG doesn't contain cycles, we represent a cycle in the graph
  299. /// using an anti dependence from a Phi to an instruction.
  300. bool isBackedge(SUnit *Source, const SDep &Dep) {
  301. if (Dep.getKind() != SDep::Anti)
  302. return false;
  303. return Source->getInstr()->isPHI() || Dep.getSUnit()->getInstr()->isPHI();
  304. }
  305. bool isLoopCarriedDep(SUnit *Source, const SDep &Dep, bool isSucc = true);
  306. /// The distance function, which indicates that operation V of iteration I
  307. /// depends on operations U of iteration I-distance.
  308. unsigned getDistance(SUnit *U, SUnit *V, const SDep &Dep) {
  309. // Instructions that feed a Phi have a distance of 1. Computing larger
  310. // values for arrays requires data dependence information.
  311. if (V->getInstr()->isPHI() && Dep.getKind() == SDep::Anti)
  312. return 1;
  313. return 0;
  314. }
  315. /// Set the Minimum Initiation Interval for this schedule attempt.
  316. void setMII(unsigned mii) { MII = mii; }
  317. void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule);
  318. void fixupRegisterOverlaps(std::deque<SUnit *> &Instrs);
  319. /// Return the new base register that was stored away for the changed
  320. /// instruction.
  321. unsigned getInstrBaseReg(SUnit *SU) {
  322. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  323. InstrChanges.find(SU);
  324. if (It != InstrChanges.end())
  325. return It->second.first;
  326. return 0;
  327. }
  328. void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
  329. Mutations.push_back(std::move(Mutation));
  330. }
  331. private:
  332. void addLoopCarriedDependences(AliasAnalysis *AA);
  333. void updatePhiDependences();
  334. void changeDependences();
  335. unsigned calculateResMII();
  336. unsigned calculateRecMII(NodeSetType &RecNodeSets);
  337. void findCircuits(NodeSetType &NodeSets);
  338. void fuseRecs(NodeSetType &NodeSets);
  339. void removeDuplicateNodes(NodeSetType &NodeSets);
  340. void computeNodeFunctions(NodeSetType &NodeSets);
  341. void registerPressureFilter(NodeSetType &NodeSets);
  342. void colocateNodeSets(NodeSetType &NodeSets);
  343. void checkNodeSets(NodeSetType &NodeSets);
  344. void groupRemainingNodes(NodeSetType &NodeSets);
  345. void addConnectedNodes(SUnit *SU, NodeSet &NewSet,
  346. SetVector<SUnit *> &NodesAdded);
  347. void computeNodeOrder(NodeSetType &NodeSets);
  348. void checkValidNodeOrder(const NodeSetType &Circuits) const;
  349. bool schedulePipeline(SMSchedule &Schedule);
  350. void generatePipelinedLoop(SMSchedule &Schedule);
  351. void generateProlog(SMSchedule &Schedule, unsigned LastStage,
  352. MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
  353. MBBVectorTy &PrologBBs);
  354. void generateEpilog(SMSchedule &Schedule, unsigned LastStage,
  355. MachineBasicBlock *KernelBB, ValueMapTy *VRMap,
  356. MBBVectorTy &EpilogBBs, MBBVectorTy &PrologBBs);
  357. void generateExistingPhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
  358. MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
  359. SMSchedule &Schedule, ValueMapTy *VRMap,
  360. InstrMapTy &InstrMap, unsigned LastStageNum,
  361. unsigned CurStageNum, bool IsLast);
  362. void generatePhis(MachineBasicBlock *NewBB, MachineBasicBlock *BB1,
  363. MachineBasicBlock *BB2, MachineBasicBlock *KernelBB,
  364. SMSchedule &Schedule, ValueMapTy *VRMap,
  365. InstrMapTy &InstrMap, unsigned LastStageNum,
  366. unsigned CurStageNum, bool IsLast);
  367. void removeDeadInstructions(MachineBasicBlock *KernelBB,
  368. MBBVectorTy &EpilogBBs);
  369. void splitLifetimes(MachineBasicBlock *KernelBB, MBBVectorTy &EpilogBBs,
  370. SMSchedule &Schedule);
  371. void addBranches(MBBVectorTy &PrologBBs, MachineBasicBlock *KernelBB,
  372. MBBVectorTy &EpilogBBs, SMSchedule &Schedule,
  373. ValueMapTy *VRMap);
  374. bool computeDelta(MachineInstr &MI, unsigned &Delta);
  375. void updateMemOperands(MachineInstr &NewMI, MachineInstr &OldMI,
  376. unsigned Num);
  377. MachineInstr *cloneInstr(MachineInstr *OldMI, unsigned CurStageNum,
  378. unsigned InstStageNum);
  379. MachineInstr *cloneAndChangeInstr(MachineInstr *OldMI, unsigned CurStageNum,
  380. unsigned InstStageNum,
  381. SMSchedule &Schedule);
  382. void updateInstruction(MachineInstr *NewMI, bool LastDef,
  383. unsigned CurStageNum, unsigned InstStageNum,
  384. SMSchedule &Schedule, ValueMapTy *VRMap);
  385. MachineInstr *findDefInLoop(unsigned Reg);
  386. unsigned getPrevMapVal(unsigned StageNum, unsigned PhiStage, unsigned LoopVal,
  387. unsigned LoopStage, ValueMapTy *VRMap,
  388. MachineBasicBlock *BB);
  389. void rewritePhiValues(MachineBasicBlock *NewBB, unsigned StageNum,
  390. SMSchedule &Schedule, ValueMapTy *VRMap,
  391. InstrMapTy &InstrMap);
  392. void rewriteScheduledInstr(MachineBasicBlock *BB, SMSchedule &Schedule,
  393. InstrMapTy &InstrMap, unsigned CurStageNum,
  394. unsigned PhiNum, MachineInstr *Phi,
  395. unsigned OldReg, unsigned NewReg,
  396. unsigned PrevReg = 0);
  397. bool canUseLastOffsetValue(MachineInstr *MI, unsigned &BasePos,
  398. unsigned &OffsetPos, unsigned &NewBase,
  399. int64_t &NewOffset);
  400. void postprocessDAG();
  401. };
  402. /// A NodeSet contains a set of SUnit DAG nodes with additional information
  403. /// that assigns a priority to the set.
  404. class NodeSet {
  405. SetVector<SUnit *> Nodes;
  406. bool HasRecurrence = false;
  407. unsigned RecMII = 0;
  408. int MaxMOV = 0;
  409. unsigned MaxDepth = 0;
  410. unsigned Colocate = 0;
  411. SUnit *ExceedPressure = nullptr;
  412. unsigned Latency = 0;
  413. public:
  414. using iterator = SetVector<SUnit *>::const_iterator;
  415. NodeSet() = default;
  416. NodeSet(iterator S, iterator E) : Nodes(S, E), HasRecurrence(true) {
  417. Latency = 0;
  418. for (unsigned i = 0, e = Nodes.size(); i < e; ++i)
  419. for (const SDep &Succ : Nodes[i]->Succs)
  420. if (Nodes.count(Succ.getSUnit()))
  421. Latency += Succ.getLatency();
  422. }
  423. bool insert(SUnit *SU) { return Nodes.insert(SU); }
  424. void insert(iterator S, iterator E) { Nodes.insert(S, E); }
  425. template <typename UnaryPredicate> bool remove_if(UnaryPredicate P) {
  426. return Nodes.remove_if(P);
  427. }
  428. unsigned count(SUnit *SU) const { return Nodes.count(SU); }
  429. bool hasRecurrence() { return HasRecurrence; };
  430. unsigned size() const { return Nodes.size(); }
  431. bool empty() const { return Nodes.empty(); }
  432. SUnit *getNode(unsigned i) const { return Nodes[i]; };
  433. void setRecMII(unsigned mii) { RecMII = mii; };
  434. void setColocate(unsigned c) { Colocate = c; };
  435. void setExceedPressure(SUnit *SU) { ExceedPressure = SU; }
  436. bool isExceedSU(SUnit *SU) { return ExceedPressure == SU; }
  437. int compareRecMII(NodeSet &RHS) { return RecMII - RHS.RecMII; }
  438. int getRecMII() { return RecMII; }
  439. /// Summarize node functions for the entire node set.
  440. void computeNodeSetInfo(SwingSchedulerDAG *SSD) {
  441. for (SUnit *SU : *this) {
  442. MaxMOV = std::max(MaxMOV, SSD->getMOV(SU));
  443. MaxDepth = std::max(MaxDepth, SSD->getDepth(SU));
  444. }
  445. }
  446. unsigned getLatency() { return Latency; }
  447. unsigned getMaxDepth() { return MaxDepth; }
  448. void clear() {
  449. Nodes.clear();
  450. RecMII = 0;
  451. HasRecurrence = false;
  452. MaxMOV = 0;
  453. MaxDepth = 0;
  454. Colocate = 0;
  455. ExceedPressure = nullptr;
  456. }
  457. operator SetVector<SUnit *> &() { return Nodes; }
  458. /// Sort the node sets by importance. First, rank them by recurrence MII,
  459. /// then by mobility (least mobile done first), and finally by depth.
  460. /// Each node set may contain a colocate value which is used as the first
  461. /// tie breaker, if it's set.
  462. bool operator>(const NodeSet &RHS) const {
  463. if (RecMII == RHS.RecMII) {
  464. if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate)
  465. return Colocate < RHS.Colocate;
  466. if (MaxMOV == RHS.MaxMOV)
  467. return MaxDepth > RHS.MaxDepth;
  468. return MaxMOV < RHS.MaxMOV;
  469. }
  470. return RecMII > RHS.RecMII;
  471. }
  472. bool operator==(const NodeSet &RHS) const {
  473. return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV &&
  474. MaxDepth == RHS.MaxDepth;
  475. }
  476. bool operator!=(const NodeSet &RHS) const { return !operator==(RHS); }
  477. iterator begin() { return Nodes.begin(); }
  478. iterator end() { return Nodes.end(); }
  479. void print(raw_ostream &os) const {
  480. os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
  481. << " depth " << MaxDepth << " col " << Colocate << "\n";
  482. for (const auto &I : Nodes)
  483. os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
  484. os << "\n";
  485. }
  486. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  487. LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
  488. #endif
  489. };
  490. /// This class repesents the scheduled code. The main data structure is a
  491. /// map from scheduled cycle to instructions. During scheduling, the
  492. /// data structure explicitly represents all stages/iterations. When
  493. /// the algorithm finshes, the schedule is collapsed into a single stage,
  494. /// which represents instructions from different loop iterations.
  495. ///
  496. /// The SMS algorithm allows negative values for cycles, so the first cycle
  497. /// in the schedule is the smallest cycle value.
  498. class SMSchedule {
  499. private:
  500. /// Map from execution cycle to instructions.
  501. DenseMap<int, std::deque<SUnit *>> ScheduledInstrs;
  502. /// Map from instruction to execution cycle.
  503. std::map<SUnit *, int> InstrToCycle;
  504. /// Map for each register and the max difference between its uses and def.
  505. /// The first element in the pair is the max difference in stages. The
  506. /// second is true if the register defines a Phi value and loop value is
  507. /// scheduled before the Phi.
  508. std::map<unsigned, std::pair<unsigned, bool>> RegToStageDiff;
  509. /// Keep track of the first cycle value in the schedule. It starts
  510. /// as zero, but the algorithm allows negative values.
  511. int FirstCycle = 0;
  512. /// Keep track of the last cycle value in the schedule.
  513. int LastCycle = 0;
  514. /// The initiation interval (II) for the schedule.
  515. int InitiationInterval = 0;
  516. /// Target machine information.
  517. const TargetSubtargetInfo &ST;
  518. /// Virtual register information.
  519. MachineRegisterInfo &MRI;
  520. std::unique_ptr<DFAPacketizer> Resources;
  521. public:
  522. SMSchedule(MachineFunction *mf)
  523. : ST(mf->getSubtarget()), MRI(mf->getRegInfo()),
  524. Resources(ST.getInstrInfo()->CreateTargetScheduleState(ST)) {}
  525. void reset() {
  526. ScheduledInstrs.clear();
  527. InstrToCycle.clear();
  528. RegToStageDiff.clear();
  529. FirstCycle = 0;
  530. LastCycle = 0;
  531. InitiationInterval = 0;
  532. }
  533. /// Set the initiation interval for this schedule.
  534. void setInitiationInterval(int ii) { InitiationInterval = ii; }
  535. /// Return the first cycle in the completed schedule. This
  536. /// can be a negative value.
  537. int getFirstCycle() const { return FirstCycle; }
  538. /// Return the last cycle in the finalized schedule.
  539. int getFinalCycle() const { return FirstCycle + InitiationInterval - 1; }
  540. /// Return the cycle of the earliest scheduled instruction in the dependence
  541. /// chain.
  542. int earliestCycleInChain(const SDep &Dep);
  543. /// Return the cycle of the latest scheduled instruction in the dependence
  544. /// chain.
  545. int latestCycleInChain(const SDep &Dep);
  546. void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
  547. int *MinEnd, int *MaxStart, int II, SwingSchedulerDAG *DAG);
  548. bool insert(SUnit *SU, int StartCycle, int EndCycle, int II);
  549. /// Iterators for the cycle to instruction map.
  550. using sched_iterator = DenseMap<int, std::deque<SUnit *>>::iterator;
  551. using const_sched_iterator =
  552. DenseMap<int, std::deque<SUnit *>>::const_iterator;
  553. /// Return true if the instruction is scheduled at the specified stage.
  554. bool isScheduledAtStage(SUnit *SU, unsigned StageNum) {
  555. return (stageScheduled(SU) == (int)StageNum);
  556. }
  557. /// Return the stage for a scheduled instruction. Return -1 if
  558. /// the instruction has not been scheduled.
  559. int stageScheduled(SUnit *SU) const {
  560. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
  561. if (it == InstrToCycle.end())
  562. return -1;
  563. return (it->second - FirstCycle) / InitiationInterval;
  564. }
  565. /// Return the cycle for a scheduled instruction. This function normalizes
  566. /// the first cycle to be 0.
  567. unsigned cycleScheduled(SUnit *SU) const {
  568. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
  569. assert(it != InstrToCycle.end() && "Instruction hasn't been scheduled.");
  570. return (it->second - FirstCycle) % InitiationInterval;
  571. }
  572. /// Return the maximum stage count needed for this schedule.
  573. unsigned getMaxStageCount() {
  574. return (LastCycle - FirstCycle) / InitiationInterval;
  575. }
  576. /// Return the max. number of stages/iterations that can occur between a
  577. /// register definition and its uses.
  578. unsigned getStagesForReg(int Reg, unsigned CurStage) {
  579. std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
  580. if (CurStage > getMaxStageCount() && Stages.first == 0 && Stages.second)
  581. return 1;
  582. return Stages.first;
  583. }
  584. /// The number of stages for a Phi is a little different than other
  585. /// instructions. The minimum value computed in RegToStageDiff is 1
  586. /// because we assume the Phi is needed for at least 1 iteration.
  587. /// This is not the case if the loop value is scheduled prior to the
  588. /// Phi in the same stage. This function returns the number of stages
  589. /// or iterations needed between the Phi definition and any uses.
  590. unsigned getStagesForPhi(int Reg) {
  591. std::pair<unsigned, bool> Stages = RegToStageDiff[Reg];
  592. if (Stages.second)
  593. return Stages.first;
  594. return Stages.first - 1;
  595. }
  596. /// Return the instructions that are scheduled at the specified cycle.
  597. std::deque<SUnit *> &getInstructions(int cycle) {
  598. return ScheduledInstrs[cycle];
  599. }
  600. bool isValidSchedule(SwingSchedulerDAG *SSD);
  601. void finalizeSchedule(SwingSchedulerDAG *SSD);
  602. void orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
  603. std::deque<SUnit *> &Insts);
  604. bool isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi);
  605. bool isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, MachineInstr *Inst,
  606. MachineOperand &MO);
  607. void print(raw_ostream &os) const;
  608. void dump() const;
  609. };
  610. } // end anonymous namespace
  611. unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
  612. char MachinePipeliner::ID = 0;
  613. #ifndef NDEBUG
  614. int MachinePipeliner::NumTries = 0;
  615. #endif
  616. char &llvm::MachinePipelinerID = MachinePipeliner::ID;
  617. INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
  618. "Modulo Software Pipelining", false, false)
  619. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  620. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  621. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  622. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  623. INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
  624. "Modulo Software Pipelining", false, false)
  625. /// The "main" function for implementing Swing Modulo Scheduling.
  626. bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
  627. if (skipFunction(mf.getFunction()))
  628. return false;
  629. if (!EnableSWP)
  630. return false;
  631. if (mf.getFunction().getAttributes().hasAttribute(
  632. AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
  633. !EnableSWPOptSize.getPosition())
  634. return false;
  635. MF = &mf;
  636. MLI = &getAnalysis<MachineLoopInfo>();
  637. MDT = &getAnalysis<MachineDominatorTree>();
  638. TII = MF->getSubtarget().getInstrInfo();
  639. RegClassInfo.runOnMachineFunction(*MF);
  640. for (auto &L : *MLI)
  641. scheduleLoop(*L);
  642. return false;
  643. }
  644. /// Attempt to perform the SMS algorithm on the specified loop. This function is
  645. /// the main entry point for the algorithm. The function identifies candidate
  646. /// loops, calculates the minimum initiation interval, and attempts to schedule
  647. /// the loop.
  648. bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
  649. bool Changed = false;
  650. for (auto &InnerLoop : L)
  651. Changed |= scheduleLoop(*InnerLoop);
  652. #ifndef NDEBUG
  653. // Stop trying after reaching the limit (if any).
  654. int Limit = SwpLoopLimit;
  655. if (Limit >= 0) {
  656. if (NumTries >= SwpLoopLimit)
  657. return Changed;
  658. NumTries++;
  659. }
  660. #endif
  661. if (!canPipelineLoop(L))
  662. return Changed;
  663. ++NumTrytoPipeline;
  664. Changed = swingModuloScheduler(L);
  665. return Changed;
  666. }
  667. /// Return true if the loop can be software pipelined. The algorithm is
  668. /// restricted to loops with a single basic block. Make sure that the
  669. /// branch in the loop can be analyzed.
  670. bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
  671. if (L.getNumBlocks() != 1)
  672. return false;
  673. // Check if the branch can't be understood because we can't do pipelining
  674. // if that's the case.
  675. LI.TBB = nullptr;
  676. LI.FBB = nullptr;
  677. LI.BrCond.clear();
  678. if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond))
  679. return false;
  680. LI.LoopInductionVar = nullptr;
  681. LI.LoopCompare = nullptr;
  682. if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare))
  683. return false;
  684. if (!L.getLoopPreheader())
  685. return false;
  686. // Remove any subregisters from inputs to phi nodes.
  687. preprocessPhiNodes(*L.getHeader());
  688. return true;
  689. }
  690. void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
  691. MachineRegisterInfo &MRI = MF->getRegInfo();
  692. SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
  693. for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
  694. MachineOperand &DefOp = PI.getOperand(0);
  695. assert(DefOp.getSubReg() == 0);
  696. auto *RC = MRI.getRegClass(DefOp.getReg());
  697. for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
  698. MachineOperand &RegOp = PI.getOperand(i);
  699. if (RegOp.getSubReg() == 0)
  700. continue;
  701. // If the operand uses a subregister, replace it with a new register
  702. // without subregisters, and generate a copy to the new register.
  703. unsigned NewReg = MRI.createVirtualRegister(RC);
  704. MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
  705. MachineBasicBlock::iterator At = PredB.getFirstTerminator();
  706. const DebugLoc &DL = PredB.findDebugLoc(At);
  707. auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
  708. .addReg(RegOp.getReg(), getRegState(RegOp),
  709. RegOp.getSubReg());
  710. Slots.insertMachineInstrInMaps(*Copy);
  711. RegOp.setReg(NewReg);
  712. RegOp.setSubReg(0);
  713. }
  714. }
  715. }
  716. /// The SMS algorithm consists of the following main steps:
  717. /// 1. Computation and analysis of the dependence graph.
  718. /// 2. Ordering of the nodes (instructions).
  719. /// 3. Attempt to Schedule the loop.
  720. bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
  721. assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
  722. SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo);
  723. MachineBasicBlock *MBB = L.getHeader();
  724. // The kernel should not include any terminator instructions. These
  725. // will be added back later.
  726. SMS.startBlock(MBB);
  727. // Compute the number of 'real' instructions in the basic block by
  728. // ignoring terminators.
  729. unsigned size = MBB->size();
  730. for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
  731. E = MBB->instr_end();
  732. I != E; ++I, --size)
  733. ;
  734. SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
  735. SMS.schedule();
  736. SMS.exitRegion();
  737. SMS.finishBlock();
  738. return SMS.hasNewSchedule();
  739. }
  740. /// We override the schedule function in ScheduleDAGInstrs to implement the
  741. /// scheduling part of the Swing Modulo Scheduling algorithm.
  742. void SwingSchedulerDAG::schedule() {
  743. AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
  744. buildSchedGraph(AA);
  745. addLoopCarriedDependences(AA);
  746. updatePhiDependences();
  747. Topo.InitDAGTopologicalSorting();
  748. postprocessDAG();
  749. changeDependences();
  750. DEBUG({
  751. for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  752. SUnits[su].dumpAll(this);
  753. });
  754. NodeSetType NodeSets;
  755. findCircuits(NodeSets);
  756. NodeSetType Circuits = NodeSets;
  757. // Calculate the MII.
  758. unsigned ResMII = calculateResMII();
  759. unsigned RecMII = calculateRecMII(NodeSets);
  760. fuseRecs(NodeSets);
  761. // This flag is used for testing and can cause correctness problems.
  762. if (SwpIgnoreRecMII)
  763. RecMII = 0;
  764. MII = std::max(ResMII, RecMII);
  765. DEBUG(dbgs() << "MII = " << MII << " (rec=" << RecMII << ", res=" << ResMII
  766. << ")\n");
  767. // Can't schedule a loop without a valid MII.
  768. if (MII == 0)
  769. return;
  770. // Don't pipeline large loops.
  771. if (SwpMaxMii != -1 && (int)MII > SwpMaxMii)
  772. return;
  773. computeNodeFunctions(NodeSets);
  774. registerPressureFilter(NodeSets);
  775. colocateNodeSets(NodeSets);
  776. checkNodeSets(NodeSets);
  777. DEBUG({
  778. for (auto &I : NodeSets) {
  779. dbgs() << " Rec NodeSet ";
  780. I.dump();
  781. }
  782. });
  783. std::stable_sort(NodeSets.begin(), NodeSets.end(), std::greater<NodeSet>());
  784. groupRemainingNodes(NodeSets);
  785. removeDuplicateNodes(NodeSets);
  786. DEBUG({
  787. for (auto &I : NodeSets) {
  788. dbgs() << " NodeSet ";
  789. I.dump();
  790. }
  791. });
  792. computeNodeOrder(NodeSets);
  793. // check for node order issues
  794. checkValidNodeOrder(Circuits);
  795. SMSchedule Schedule(Pass.MF);
  796. Scheduled = schedulePipeline(Schedule);
  797. if (!Scheduled)
  798. return;
  799. unsigned numStages = Schedule.getMaxStageCount();
  800. // No need to generate pipeline if there are no overlapped iterations.
  801. if (numStages == 0)
  802. return;
  803. // Check that the maximum stage count is less than user-defined limit.
  804. if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages)
  805. return;
  806. generatePipelinedLoop(Schedule);
  807. ++NumPipelined;
  808. }
  809. /// Clean up after the software pipeliner runs.
  810. void SwingSchedulerDAG::finishBlock() {
  811. for (MachineInstr *I : NewMIs)
  812. MF.DeleteMachineInstr(I);
  813. NewMIs.clear();
  814. // Call the superclass.
  815. ScheduleDAGInstrs::finishBlock();
  816. }
  817. /// Return the register values for the operands of a Phi instruction.
  818. /// This function assume the instruction is a Phi.
  819. static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
  820. unsigned &InitVal, unsigned &LoopVal) {
  821. assert(Phi.isPHI() && "Expecting a Phi.");
  822. InitVal = 0;
  823. LoopVal = 0;
  824. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  825. if (Phi.getOperand(i + 1).getMBB() != Loop)
  826. InitVal = Phi.getOperand(i).getReg();
  827. else
  828. LoopVal = Phi.getOperand(i).getReg();
  829. assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
  830. }
  831. /// Return the Phi register value that comes from the incoming block.
  832. static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
  833. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  834. if (Phi.getOperand(i + 1).getMBB() != LoopBB)
  835. return Phi.getOperand(i).getReg();
  836. return 0;
  837. }
  838. /// Return the Phi register value that comes the loop block.
  839. static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
  840. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  841. if (Phi.getOperand(i + 1).getMBB() == LoopBB)
  842. return Phi.getOperand(i).getReg();
  843. return 0;
  844. }
  845. /// Return true if SUb can be reached from SUa following the chain edges.
  846. static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
  847. SmallPtrSet<SUnit *, 8> Visited;
  848. SmallVector<SUnit *, 8> Worklist;
  849. Worklist.push_back(SUa);
  850. while (!Worklist.empty()) {
  851. const SUnit *SU = Worklist.pop_back_val();
  852. for (auto &SI : SU->Succs) {
  853. SUnit *SuccSU = SI.getSUnit();
  854. if (SI.getKind() == SDep::Order) {
  855. if (Visited.count(SuccSU))
  856. continue;
  857. if (SuccSU == SUb)
  858. return true;
  859. Worklist.push_back(SuccSU);
  860. Visited.insert(SuccSU);
  861. }
  862. }
  863. }
  864. return false;
  865. }
  866. /// Return true if the instruction causes a chain between memory
  867. /// references before and after it.
  868. static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
  869. return MI.isCall() || MI.hasUnmodeledSideEffects() ||
  870. (MI.hasOrderedMemoryRef() &&
  871. (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
  872. }
  873. /// Return the underlying objects for the memory references of an instruction.
  874. /// This function calls the code in ValueTracking, but first checks that the
  875. /// instruction has a memory operand.
  876. static void getUnderlyingObjects(MachineInstr *MI,
  877. SmallVectorImpl<Value *> &Objs,
  878. const DataLayout &DL) {
  879. if (!MI->hasOneMemOperand())
  880. return;
  881. MachineMemOperand *MM = *MI->memoperands_begin();
  882. if (!MM->getValue())
  883. return;
  884. GetUnderlyingObjects(const_cast<Value *>(MM->getValue()), Objs, DL);
  885. for (Value *V : Objs) {
  886. if (!isIdentifiedObject(V)) {
  887. Objs.clear();
  888. return;
  889. }
  890. Objs.push_back(V);
  891. }
  892. }
  893. /// Add a chain edge between a load and store if the store can be an
  894. /// alias of the load on a subsequent iteration, i.e., a loop carried
  895. /// dependence. This code is very similar to the code in ScheduleDAGInstrs
  896. /// but that code doesn't create loop carried dependences.
  897. void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
  898. MapVector<Value *, SmallVector<SUnit *, 4>> PendingLoads;
  899. Value *UnknownValue =
  900. UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
  901. for (auto &SU : SUnits) {
  902. MachineInstr &MI = *SU.getInstr();
  903. if (isDependenceBarrier(MI, AA))
  904. PendingLoads.clear();
  905. else if (MI.mayLoad()) {
  906. SmallVector<Value *, 4> Objs;
  907. getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
  908. if (Objs.empty())
  909. Objs.push_back(UnknownValue);
  910. for (auto V : Objs) {
  911. SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
  912. SUs.push_back(&SU);
  913. }
  914. } else if (MI.mayStore()) {
  915. SmallVector<Value *, 4> Objs;
  916. getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
  917. if (Objs.empty())
  918. Objs.push_back(UnknownValue);
  919. for (auto V : Objs) {
  920. MapVector<Value *, SmallVector<SUnit *, 4>>::iterator I =
  921. PendingLoads.find(V);
  922. if (I == PendingLoads.end())
  923. continue;
  924. for (auto Load : I->second) {
  925. if (isSuccOrder(Load, &SU))
  926. continue;
  927. MachineInstr &LdMI = *Load->getInstr();
  928. // First, perform the cheaper check that compares the base register.
  929. // If they are the same and the load offset is less than the store
  930. // offset, then mark the dependence as loop carried potentially.
  931. unsigned BaseReg1, BaseReg2;
  932. int64_t Offset1, Offset2;
  933. if (TII->getMemOpBaseRegImmOfs(LdMI, BaseReg1, Offset1, TRI) &&
  934. TII->getMemOpBaseRegImmOfs(MI, BaseReg2, Offset2, TRI)) {
  935. if (BaseReg1 == BaseReg2 && (int)Offset1 < (int)Offset2) {
  936. assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
  937. "What happened to the chain edge?");
  938. SDep Dep(Load, SDep::Barrier);
  939. Dep.setLatency(1);
  940. SU.addPred(Dep);
  941. continue;
  942. }
  943. }
  944. // Second, the more expensive check that uses alias analysis on the
  945. // base registers. If they alias, and the load offset is less than
  946. // the store offset, the mark the dependence as loop carried.
  947. if (!AA) {
  948. SDep Dep(Load, SDep::Barrier);
  949. Dep.setLatency(1);
  950. SU.addPred(Dep);
  951. continue;
  952. }
  953. MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
  954. MachineMemOperand *MMO2 = *MI.memoperands_begin();
  955. if (!MMO1->getValue() || !MMO2->getValue()) {
  956. SDep Dep(Load, SDep::Barrier);
  957. Dep.setLatency(1);
  958. SU.addPred(Dep);
  959. continue;
  960. }
  961. if (MMO1->getValue() == MMO2->getValue() &&
  962. MMO1->getOffset() <= MMO2->getOffset()) {
  963. SDep Dep(Load, SDep::Barrier);
  964. Dep.setLatency(1);
  965. SU.addPred(Dep);
  966. continue;
  967. }
  968. AliasResult AAResult = AA->alias(
  969. MemoryLocation(MMO1->getValue(), MemoryLocation::UnknownSize,
  970. MMO1->getAAInfo()),
  971. MemoryLocation(MMO2->getValue(), MemoryLocation::UnknownSize,
  972. MMO2->getAAInfo()));
  973. if (AAResult != NoAlias) {
  974. SDep Dep(Load, SDep::Barrier);
  975. Dep.setLatency(1);
  976. SU.addPred(Dep);
  977. }
  978. }
  979. }
  980. }
  981. }
  982. }
  983. /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
  984. /// processes dependences for PHIs. This function adds true dependences
  985. /// from a PHI to a use, and a loop carried dependence from the use to the
  986. /// PHI. The loop carried dependence is represented as an anti dependence
  987. /// edge. This function also removes chain dependences between unrelated
  988. /// PHIs.
  989. void SwingSchedulerDAG::updatePhiDependences() {
  990. SmallVector<SDep, 4> RemoveDeps;
  991. const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
  992. // Iterate over each DAG node.
  993. for (SUnit &I : SUnits) {
  994. RemoveDeps.clear();
  995. // Set to true if the instruction has an operand defined by a Phi.
  996. unsigned HasPhiUse = 0;
  997. unsigned HasPhiDef = 0;
  998. MachineInstr *MI = I.getInstr();
  999. // Iterate over each operand, and we process the definitions.
  1000. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  1001. MOE = MI->operands_end();
  1002. MOI != MOE; ++MOI) {
  1003. if (!MOI->isReg())
  1004. continue;
  1005. unsigned Reg = MOI->getReg();
  1006. if (MOI->isDef()) {
  1007. // If the register is used by a Phi, then create an anti dependence.
  1008. for (MachineRegisterInfo::use_instr_iterator
  1009. UI = MRI.use_instr_begin(Reg),
  1010. UE = MRI.use_instr_end();
  1011. UI != UE; ++UI) {
  1012. MachineInstr *UseMI = &*UI;
  1013. SUnit *SU = getSUnit(UseMI);
  1014. if (SU != nullptr && UseMI->isPHI()) {
  1015. if (!MI->isPHI()) {
  1016. SDep Dep(SU, SDep::Anti, Reg);
  1017. Dep.setLatency(1);
  1018. I.addPred(Dep);
  1019. } else {
  1020. HasPhiDef = Reg;
  1021. // Add a chain edge to a dependent Phi that isn't an existing
  1022. // predecessor.
  1023. if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
  1024. I.addPred(SDep(SU, SDep::Barrier));
  1025. }
  1026. }
  1027. }
  1028. } else if (MOI->isUse()) {
  1029. // If the register is defined by a Phi, then create a true dependence.
  1030. MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
  1031. if (DefMI == nullptr)
  1032. continue;
  1033. SUnit *SU = getSUnit(DefMI);
  1034. if (SU != nullptr && DefMI->isPHI()) {
  1035. if (!MI->isPHI()) {
  1036. SDep Dep(SU, SDep::Data, Reg);
  1037. Dep.setLatency(0);
  1038. ST.adjustSchedDependency(SU, &I, Dep);
  1039. I.addPred(Dep);
  1040. } else {
  1041. HasPhiUse = Reg;
  1042. // Add a chain edge to a dependent Phi that isn't an existing
  1043. // predecessor.
  1044. if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
  1045. I.addPred(SDep(SU, SDep::Barrier));
  1046. }
  1047. }
  1048. }
  1049. }
  1050. // Remove order dependences from an unrelated Phi.
  1051. if (!SwpPruneDeps)
  1052. continue;
  1053. for (auto &PI : I.Preds) {
  1054. MachineInstr *PMI = PI.getSUnit()->getInstr();
  1055. if (PMI->isPHI() && PI.getKind() == SDep::Order) {
  1056. if (I.getInstr()->isPHI()) {
  1057. if (PMI->getOperand(0).getReg() == HasPhiUse)
  1058. continue;
  1059. if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
  1060. continue;
  1061. }
  1062. RemoveDeps.push_back(PI);
  1063. }
  1064. }
  1065. for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
  1066. I.removePred(RemoveDeps[i]);
  1067. }
  1068. }
  1069. /// Iterate over each DAG node and see if we can change any dependences
  1070. /// in order to reduce the recurrence MII.
  1071. void SwingSchedulerDAG::changeDependences() {
  1072. // See if an instruction can use a value from the previous iteration.
  1073. // If so, we update the base and offset of the instruction and change
  1074. // the dependences.
  1075. for (SUnit &I : SUnits) {
  1076. unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
  1077. int64_t NewOffset = 0;
  1078. if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
  1079. NewOffset))
  1080. continue;
  1081. // Get the MI and SUnit for the instruction that defines the original base.
  1082. unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
  1083. MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
  1084. if (!DefMI)
  1085. continue;
  1086. SUnit *DefSU = getSUnit(DefMI);
  1087. if (!DefSU)
  1088. continue;
  1089. // Get the MI and SUnit for the instruction that defins the new base.
  1090. MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
  1091. if (!LastMI)
  1092. continue;
  1093. SUnit *LastSU = getSUnit(LastMI);
  1094. if (!LastSU)
  1095. continue;
  1096. if (Topo.IsReachable(&I, LastSU))
  1097. continue;
  1098. // Remove the dependence. The value now depends on a prior iteration.
  1099. SmallVector<SDep, 4> Deps;
  1100. for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
  1101. ++P)
  1102. if (P->getSUnit() == DefSU)
  1103. Deps.push_back(*P);
  1104. for (int i = 0, e = Deps.size(); i != e; i++) {
  1105. Topo.RemovePred(&I, Deps[i].getSUnit());
  1106. I.removePred(Deps[i]);
  1107. }
  1108. // Remove the chain dependence between the instructions.
  1109. Deps.clear();
  1110. for (auto &P : LastSU->Preds)
  1111. if (P.getSUnit() == &I && P.getKind() == SDep::Order)
  1112. Deps.push_back(P);
  1113. for (int i = 0, e = Deps.size(); i != e; i++) {
  1114. Topo.RemovePred(LastSU, Deps[i].getSUnit());
  1115. LastSU->removePred(Deps[i]);
  1116. }
  1117. // Add a dependence between the new instruction and the instruction
  1118. // that defines the new base.
  1119. SDep Dep(&I, SDep::Anti, NewBase);
  1120. LastSU->addPred(Dep);
  1121. // Remember the base and offset information so that we can update the
  1122. // instruction during code generation.
  1123. InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
  1124. }
  1125. }
  1126. namespace {
  1127. // FuncUnitSorter - Comparison operator used to sort instructions by
  1128. // the number of functional unit choices.
  1129. struct FuncUnitSorter {
  1130. const InstrItineraryData *InstrItins;
  1131. DenseMap<unsigned, unsigned> Resources;
  1132. FuncUnitSorter(const InstrItineraryData *IID) : InstrItins(IID) {}
  1133. // Compute the number of functional unit alternatives needed
  1134. // at each stage, and take the minimum value. We prioritize the
  1135. // instructions by the least number of choices first.
  1136. unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
  1137. unsigned schedClass = Inst->getDesc().getSchedClass();
  1138. unsigned min = UINT_MAX;
  1139. for (const InstrStage *IS = InstrItins->beginStage(schedClass),
  1140. *IE = InstrItins->endStage(schedClass);
  1141. IS != IE; ++IS) {
  1142. unsigned funcUnits = IS->getUnits();
  1143. unsigned numAlternatives = countPopulation(funcUnits);
  1144. if (numAlternatives < min) {
  1145. min = numAlternatives;
  1146. F = funcUnits;
  1147. }
  1148. }
  1149. return min;
  1150. }
  1151. // Compute the critical resources needed by the instruction. This
  1152. // function records the functional units needed by instructions that
  1153. // must use only one functional unit. We use this as a tie breaker
  1154. // for computing the resource MII. The instrutions that require
  1155. // the same, highly used, functional unit have high priority.
  1156. void calcCriticalResources(MachineInstr &MI) {
  1157. unsigned SchedClass = MI.getDesc().getSchedClass();
  1158. for (const InstrStage *IS = InstrItins->beginStage(SchedClass),
  1159. *IE = InstrItins->endStage(SchedClass);
  1160. IS != IE; ++IS) {
  1161. unsigned FuncUnits = IS->getUnits();
  1162. if (countPopulation(FuncUnits) == 1)
  1163. Resources[FuncUnits]++;
  1164. }
  1165. }
  1166. /// Return true if IS1 has less priority than IS2.
  1167. bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
  1168. unsigned F1 = 0, F2 = 0;
  1169. unsigned MFUs1 = minFuncUnits(IS1, F1);
  1170. unsigned MFUs2 = minFuncUnits(IS2, F2);
  1171. if (MFUs1 == 1 && MFUs2 == 1)
  1172. return Resources.lookup(F1) < Resources.lookup(F2);
  1173. return MFUs1 > MFUs2;
  1174. }
  1175. };
  1176. } // end anonymous namespace
  1177. /// Calculate the resource constrained minimum initiation interval for the
  1178. /// specified loop. We use the DFA to model the resources needed for
  1179. /// each instruction, and we ignore dependences. A different DFA is created
  1180. /// for each cycle that is required. When adding a new instruction, we attempt
  1181. /// to add it to each existing DFA, until a legal space is found. If the
  1182. /// instruction cannot be reserved in an existing DFA, we create a new one.
  1183. unsigned SwingSchedulerDAG::calculateResMII() {
  1184. SmallVector<DFAPacketizer *, 8> Resources;
  1185. MachineBasicBlock *MBB = Loop.getHeader();
  1186. Resources.push_back(TII->CreateTargetScheduleState(MF.getSubtarget()));
  1187. // Sort the instructions by the number of available choices for scheduling,
  1188. // least to most. Use the number of critical resources as the tie breaker.
  1189. FuncUnitSorter FUS =
  1190. FuncUnitSorter(MF.getSubtarget().getInstrItineraryData());
  1191. for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
  1192. E = MBB->getFirstTerminator();
  1193. I != E; ++I)
  1194. FUS.calcCriticalResources(*I);
  1195. PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
  1196. FuncUnitOrder(FUS);
  1197. for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
  1198. E = MBB->getFirstTerminator();
  1199. I != E; ++I)
  1200. FuncUnitOrder.push(&*I);
  1201. while (!FuncUnitOrder.empty()) {
  1202. MachineInstr *MI = FuncUnitOrder.top();
  1203. FuncUnitOrder.pop();
  1204. if (TII->isZeroCost(MI->getOpcode()))
  1205. continue;
  1206. // Attempt to reserve the instruction in an existing DFA. At least one
  1207. // DFA is needed for each cycle.
  1208. unsigned NumCycles = getSUnit(MI)->Latency;
  1209. unsigned ReservedCycles = 0;
  1210. SmallVectorImpl<DFAPacketizer *>::iterator RI = Resources.begin();
  1211. SmallVectorImpl<DFAPacketizer *>::iterator RE = Resources.end();
  1212. for (unsigned C = 0; C < NumCycles; ++C)
  1213. while (RI != RE) {
  1214. if ((*RI++)->canReserveResources(*MI)) {
  1215. ++ReservedCycles;
  1216. break;
  1217. }
  1218. }
  1219. // Start reserving resources using existing DFAs.
  1220. for (unsigned C = 0; C < ReservedCycles; ++C) {
  1221. --RI;
  1222. (*RI)->reserveResources(*MI);
  1223. }
  1224. // Add new DFAs, if needed, to reserve resources.
  1225. for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
  1226. DFAPacketizer *NewResource =
  1227. TII->CreateTargetScheduleState(MF.getSubtarget());
  1228. assert(NewResource->canReserveResources(*MI) && "Reserve error.");
  1229. NewResource->reserveResources(*MI);
  1230. Resources.push_back(NewResource);
  1231. }
  1232. }
  1233. int Resmii = Resources.size();
  1234. // Delete the memory for each of the DFAs that were created earlier.
  1235. for (DFAPacketizer *RI : Resources) {
  1236. DFAPacketizer *D = RI;
  1237. delete D;
  1238. }
  1239. Resources.clear();
  1240. return Resmii;
  1241. }
  1242. /// Calculate the recurrence-constrainted minimum initiation interval.
  1243. /// Iterate over each circuit. Compute the delay(c) and distance(c)
  1244. /// for each circuit. The II needs to satisfy the inequality
  1245. /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
  1246. /// II that satistifies the inequality, and the RecMII is the maximum
  1247. /// of those values.
  1248. unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
  1249. unsigned RecMII = 0;
  1250. for (NodeSet &Nodes : NodeSets) {
  1251. if (Nodes.empty())
  1252. continue;
  1253. unsigned Delay = Nodes.getLatency();
  1254. unsigned Distance = 1;
  1255. // ii = ceil(delay / distance)
  1256. unsigned CurMII = (Delay + Distance - 1) / Distance;
  1257. Nodes.setRecMII(CurMII);
  1258. if (CurMII > RecMII)
  1259. RecMII = CurMII;
  1260. }
  1261. return RecMII;
  1262. }
  1263. /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
  1264. /// but we do this to find the circuits, and then change them back.
  1265. static void swapAntiDependences(std::vector<SUnit> &SUnits) {
  1266. SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
  1267. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  1268. SUnit *SU = &SUnits[i];
  1269. for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
  1270. IP != EP; ++IP) {
  1271. if (IP->getKind() != SDep::Anti)
  1272. continue;
  1273. DepsAdded.push_back(std::make_pair(SU, *IP));
  1274. }
  1275. }
  1276. for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
  1277. E = DepsAdded.end();
  1278. I != E; ++I) {
  1279. // Remove this anti dependency and add one in the reverse direction.
  1280. SUnit *SU = I->first;
  1281. SDep &D = I->second;
  1282. SUnit *TargetSU = D.getSUnit();
  1283. unsigned Reg = D.getReg();
  1284. unsigned Lat = D.getLatency();
  1285. SU->removePred(D);
  1286. SDep Dep(SU, SDep::Anti, Reg);
  1287. Dep.setLatency(Lat);
  1288. TargetSU->addPred(Dep);
  1289. }
  1290. }
  1291. /// Create the adjacency structure of the nodes in the graph.
  1292. void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
  1293. SwingSchedulerDAG *DAG) {
  1294. BitVector Added(SUnits.size());
  1295. DenseMap<int, int> OutputDeps;
  1296. for (int i = 0, e = SUnits.size(); i != e; ++i) {
  1297. Added.reset();
  1298. // Add any successor to the adjacency matrix and exclude duplicates.
  1299. for (auto &SI : SUnits[i].Succs) {
  1300. // Only create a back-edge on the first and last nodes of a dependence
  1301. // chain. This records any chains and adds them later.
  1302. if (SI.getKind() == SDep::Output) {
  1303. int N = SI.getSUnit()->NodeNum;
  1304. int BackEdge = i;
  1305. auto Dep = OutputDeps.find(BackEdge);
  1306. if (Dep != OutputDeps.end()) {
  1307. BackEdge = Dep->second;
  1308. OutputDeps.erase(Dep);
  1309. }
  1310. OutputDeps[N] = BackEdge;
  1311. }
  1312. // Do not process a boundary node and a back-edge is processed only
  1313. // if it goes to a Phi.
  1314. if (SI.getSUnit()->isBoundaryNode() ||
  1315. (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
  1316. continue;
  1317. int N = SI.getSUnit()->NodeNum;
  1318. if (!Added.test(N)) {
  1319. AdjK[i].push_back(N);
  1320. Added.set(N);
  1321. }
  1322. }
  1323. // A chain edge between a store and a load is treated as a back-edge in the
  1324. // adjacency matrix.
  1325. for (auto &PI : SUnits[i].Preds) {
  1326. if (!SUnits[i].getInstr()->mayStore() ||
  1327. !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
  1328. continue;
  1329. if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
  1330. int N = PI.getSUnit()->NodeNum;
  1331. if (!Added.test(N)) {
  1332. AdjK[i].push_back(N);
  1333. Added.set(N);
  1334. }
  1335. }
  1336. }
  1337. }
  1338. // Add back-eges in the adjacency matrix for the output dependences.
  1339. for (auto &OD : OutputDeps)
  1340. if (!Added.test(OD.second)) {
  1341. AdjK[OD.first].push_back(OD.second);
  1342. Added.set(OD.second);
  1343. }
  1344. }
  1345. /// Identify an elementary circuit in the dependence graph starting at the
  1346. /// specified node.
  1347. bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
  1348. bool HasBackedge) {
  1349. SUnit *SV = &SUnits[V];
  1350. bool F = false;
  1351. Stack.insert(SV);
  1352. Blocked.set(V);
  1353. for (auto W : AdjK[V]) {
  1354. if (NumPaths > MaxPaths)
  1355. break;
  1356. if (W < S)
  1357. continue;
  1358. if (W == S) {
  1359. if (!HasBackedge)
  1360. NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
  1361. F = true;
  1362. ++NumPaths;
  1363. break;
  1364. } else if (!Blocked.test(W)) {
  1365. if (circuit(W, S, NodeSets, W < V ? true : HasBackedge))
  1366. F = true;
  1367. }
  1368. }
  1369. if (F)
  1370. unblock(V);
  1371. else {
  1372. for (auto W : AdjK[V]) {
  1373. if (W < S)
  1374. continue;
  1375. if (B[W].count(SV) == 0)
  1376. B[W].insert(SV);
  1377. }
  1378. }
  1379. Stack.pop_back();
  1380. return F;
  1381. }
  1382. /// Unblock a node in the circuit finding algorithm.
  1383. void SwingSchedulerDAG::Circuits::unblock(int U) {
  1384. Blocked.reset(U);
  1385. SmallPtrSet<SUnit *, 4> &BU = B[U];
  1386. while (!BU.empty()) {
  1387. SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
  1388. assert(SI != BU.end() && "Invalid B set.");
  1389. SUnit *W = *SI;
  1390. BU.erase(W);
  1391. if (Blocked.test(W->NodeNum))
  1392. unblock(W->NodeNum);
  1393. }
  1394. }
  1395. /// Identify all the elementary circuits in the dependence graph using
  1396. /// Johnson's circuit algorithm.
  1397. void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
  1398. // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
  1399. // but we do this to find the circuits, and then change them back.
  1400. swapAntiDependences(SUnits);
  1401. Circuits Cir(SUnits);
  1402. // Create the adjacency structure.
  1403. Cir.createAdjacencyStructure(this);
  1404. for (int i = 0, e = SUnits.size(); i != e; ++i) {
  1405. Cir.reset();
  1406. Cir.circuit(i, i, NodeSets);
  1407. }
  1408. // Change the dependences back so that we've created a DAG again.
  1409. swapAntiDependences(SUnits);
  1410. }
  1411. /// Return true for DAG nodes that we ignore when computing the cost functions.
  1412. /// We ignore the back-edge recurrence in order to avoid unbounded recurison
  1413. /// in the calculation of the ASAP, ALAP, etc functions.
  1414. static bool ignoreDependence(const SDep &D, bool isPred) {
  1415. if (D.isArtificial())
  1416. return true;
  1417. return D.getKind() == SDep::Anti && isPred;
  1418. }
  1419. /// Compute several functions need to order the nodes for scheduling.
  1420. /// ASAP - Earliest time to schedule a node.
  1421. /// ALAP - Latest time to schedule a node.
  1422. /// MOV - Mobility function, difference between ALAP and ASAP.
  1423. /// D - Depth of each node.
  1424. /// H - Height of each node.
  1425. void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
  1426. ScheduleInfo.resize(SUnits.size());
  1427. DEBUG({
  1428. for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
  1429. E = Topo.end();
  1430. I != E; ++I) {
  1431. SUnit *SU = &SUnits[*I];
  1432. SU->dump(this);
  1433. }
  1434. });
  1435. int maxASAP = 0;
  1436. // Compute ASAP and ZeroLatencyDepth.
  1437. for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
  1438. E = Topo.end();
  1439. I != E; ++I) {
  1440. int asap = 0;
  1441. int zeroLatencyDepth = 0;
  1442. SUnit *SU = &SUnits[*I];
  1443. for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
  1444. EP = SU->Preds.end();
  1445. IP != EP; ++IP) {
  1446. SUnit *pred = IP->getSUnit();
  1447. if (IP->getLatency() == 0)
  1448. zeroLatencyDepth =
  1449. std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
  1450. if (ignoreDependence(*IP, true))
  1451. continue;
  1452. asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
  1453. getDistance(pred, SU, *IP) * MII));
  1454. }
  1455. maxASAP = std::max(maxASAP, asap);
  1456. ScheduleInfo[*I].ASAP = asap;
  1457. ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
  1458. }
  1459. // Compute ALAP, ZeroLatencyHeight, and MOV.
  1460. for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
  1461. E = Topo.rend();
  1462. I != E; ++I) {
  1463. int alap = maxASAP;
  1464. int zeroLatencyHeight = 0;
  1465. SUnit *SU = &SUnits[*I];
  1466. for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
  1467. ES = SU->Succs.end();
  1468. IS != ES; ++IS) {
  1469. SUnit *succ = IS->getSUnit();
  1470. if (IS->getLatency() == 0)
  1471. zeroLatencyHeight =
  1472. std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
  1473. if (ignoreDependence(*IS, true))
  1474. continue;
  1475. alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
  1476. getDistance(SU, succ, *IS) * MII));
  1477. }
  1478. ScheduleInfo[*I].ALAP = alap;
  1479. ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
  1480. }
  1481. // After computing the node functions, compute the summary for each node set.
  1482. for (NodeSet &I : NodeSets)
  1483. I.computeNodeSetInfo(this);
  1484. DEBUG({
  1485. for (unsigned i = 0; i < SUnits.size(); i++) {
  1486. dbgs() << "\tNode " << i << ":\n";
  1487. dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
  1488. dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
  1489. dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
  1490. dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
  1491. dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
  1492. dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
  1493. dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
  1494. }
  1495. });
  1496. }
  1497. /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
  1498. /// as the predecessors of the elements of NodeOrder that are not also in
  1499. /// NodeOrder.
  1500. static bool pred_L(SetVector<SUnit *> &NodeOrder,
  1501. SmallSetVector<SUnit *, 8> &Preds,
  1502. const NodeSet *S = nullptr) {
  1503. Preds.clear();
  1504. for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
  1505. I != E; ++I) {
  1506. for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
  1507. PI != PE; ++PI) {
  1508. if (S && S->count(PI->getSUnit()) == 0)
  1509. continue;
  1510. if (ignoreDependence(*PI, true))
  1511. continue;
  1512. if (NodeOrder.count(PI->getSUnit()) == 0)
  1513. Preds.insert(PI->getSUnit());
  1514. }
  1515. // Back-edges are predecessors with an anti-dependence.
  1516. for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
  1517. ES = (*I)->Succs.end();
  1518. IS != ES; ++IS) {
  1519. if (IS->getKind() != SDep::Anti)
  1520. continue;
  1521. if (S && S->count(IS->getSUnit()) == 0)
  1522. continue;
  1523. if (NodeOrder.count(IS->getSUnit()) == 0)
  1524. Preds.insert(IS->getSUnit());
  1525. }
  1526. }
  1527. return !Preds.empty();
  1528. }
  1529. /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
  1530. /// as the successors of the elements of NodeOrder that are not also in
  1531. /// NodeOrder.
  1532. static bool succ_L(SetVector<SUnit *> &NodeOrder,
  1533. SmallSetVector<SUnit *, 8> &Succs,
  1534. const NodeSet *S = nullptr) {
  1535. Succs.clear();
  1536. for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
  1537. I != E; ++I) {
  1538. for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
  1539. SI != SE; ++SI) {
  1540. if (S && S->count(SI->getSUnit()) == 0)
  1541. continue;
  1542. if (ignoreDependence(*SI, false))
  1543. continue;
  1544. if (NodeOrder.count(SI->getSUnit()) == 0)
  1545. Succs.insert(SI->getSUnit());
  1546. }
  1547. for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
  1548. PE = (*I)->Preds.end();
  1549. PI != PE; ++PI) {
  1550. if (PI->getKind() != SDep::Anti)
  1551. continue;
  1552. if (S && S->count(PI->getSUnit()) == 0)
  1553. continue;
  1554. if (NodeOrder.count(PI->getSUnit()) == 0)
  1555. Succs.insert(PI->getSUnit());
  1556. }
  1557. }
  1558. return !Succs.empty();
  1559. }
  1560. /// Return true if there is a path from the specified node to any of the nodes
  1561. /// in DestNodes. Keep track and return the nodes in any path.
  1562. static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
  1563. SetVector<SUnit *> &DestNodes,
  1564. SetVector<SUnit *> &Exclude,
  1565. SmallPtrSet<SUnit *, 8> &Visited) {
  1566. if (Cur->isBoundaryNode())
  1567. return false;
  1568. if (Exclude.count(Cur) != 0)
  1569. return false;
  1570. if (DestNodes.count(Cur) != 0)
  1571. return true;
  1572. if (!Visited.insert(Cur).second)
  1573. return Path.count(Cur) != 0;
  1574. bool FoundPath = false;
  1575. for (auto &SI : Cur->Succs)
  1576. FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
  1577. for (auto &PI : Cur->Preds)
  1578. if (PI.getKind() == SDep::Anti)
  1579. FoundPath |=
  1580. computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
  1581. if (FoundPath)
  1582. Path.insert(Cur);
  1583. return FoundPath;
  1584. }
  1585. /// Return true if Set1 is a subset of Set2.
  1586. template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
  1587. for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
  1588. if (Set2.count(*I) == 0)
  1589. return false;
  1590. return true;
  1591. }
  1592. /// Compute the live-out registers for the instructions in a node-set.
  1593. /// The live-out registers are those that are defined in the node-set,
  1594. /// but not used. Except for use operands of Phis.
  1595. static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
  1596. NodeSet &NS) {
  1597. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1598. MachineRegisterInfo &MRI = MF.getRegInfo();
  1599. SmallVector<RegisterMaskPair, 8> LiveOutRegs;
  1600. SmallSet<unsigned, 4> Uses;
  1601. for (SUnit *SU : NS) {
  1602. const MachineInstr *MI = SU->getInstr();
  1603. if (MI->isPHI())
  1604. continue;
  1605. for (const MachineOperand &MO : MI->operands())
  1606. if (MO.isReg() && MO.isUse()) {
  1607. unsigned Reg = MO.getReg();
  1608. if (TargetRegisterInfo::isVirtualRegister(Reg))
  1609. Uses.insert(Reg);
  1610. else if (MRI.isAllocatable(Reg))
  1611. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  1612. Uses.insert(*Units);
  1613. }
  1614. }
  1615. for (SUnit *SU : NS)
  1616. for (const MachineOperand &MO : SU->getInstr()->operands())
  1617. if (MO.isReg() && MO.isDef() && !MO.isDead()) {
  1618. unsigned Reg = MO.getReg();
  1619. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  1620. if (!Uses.count(Reg))
  1621. LiveOutRegs.push_back(RegisterMaskPair(Reg,
  1622. LaneBitmask::getNone()));
  1623. } else if (MRI.isAllocatable(Reg)) {
  1624. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  1625. if (!Uses.count(*Units))
  1626. LiveOutRegs.push_back(RegisterMaskPair(*Units,
  1627. LaneBitmask::getNone()));
  1628. }
  1629. }
  1630. RPTracker.addLiveRegs(LiveOutRegs);
  1631. }
  1632. /// A heuristic to filter nodes in recurrent node-sets if the register
  1633. /// pressure of a set is too high.
  1634. void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
  1635. for (auto &NS : NodeSets) {
  1636. // Skip small node-sets since they won't cause register pressure problems.
  1637. if (NS.size() <= 2)
  1638. continue;
  1639. IntervalPressure RecRegPressure;
  1640. RegPressureTracker RecRPTracker(RecRegPressure);
  1641. RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
  1642. computeLiveOuts(MF, RecRPTracker, NS);
  1643. RecRPTracker.closeBottom();
  1644. std::vector<SUnit *> SUnits(NS.begin(), NS.end());
  1645. llvm::sort(SUnits.begin(), SUnits.end(),
  1646. [](const SUnit *A, const SUnit *B) {
  1647. return A->NodeNum > B->NodeNum;
  1648. });
  1649. for (auto &SU : SUnits) {
  1650. // Since we're computing the register pressure for a subset of the
  1651. // instructions in a block, we need to set the tracker for each
  1652. // instruction in the node-set. The tracker is set to the instruction
  1653. // just after the one we're interested in.
  1654. MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
  1655. RecRPTracker.setPos(std::next(CurInstI));
  1656. RegPressureDelta RPDelta;
  1657. ArrayRef<PressureChange> CriticalPSets;
  1658. RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
  1659. CriticalPSets,
  1660. RecRegPressure.MaxSetPressure);
  1661. if (RPDelta.Excess.isValid()) {
  1662. DEBUG(dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
  1663. << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
  1664. << ":" << RPDelta.Excess.getUnitInc());
  1665. NS.setExceedPressure(SU);
  1666. break;
  1667. }
  1668. RecRPTracker.recede();
  1669. }
  1670. }
  1671. }
  1672. /// A heuristic to colocate node sets that have the same set of
  1673. /// successors.
  1674. void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
  1675. unsigned Colocate = 0;
  1676. for (int i = 0, e = NodeSets.size(); i < e; ++i) {
  1677. NodeSet &N1 = NodeSets[i];
  1678. SmallSetVector<SUnit *, 8> S1;
  1679. if (N1.empty() || !succ_L(N1, S1))
  1680. continue;
  1681. for (int j = i + 1; j < e; ++j) {
  1682. NodeSet &N2 = NodeSets[j];
  1683. if (N1.compareRecMII(N2) != 0)
  1684. continue;
  1685. SmallSetVector<SUnit *, 8> S2;
  1686. if (N2.empty() || !succ_L(N2, S2))
  1687. continue;
  1688. if (isSubset(S1, S2) && S1.size() == S2.size()) {
  1689. N1.setColocate(++Colocate);
  1690. N2.setColocate(Colocate);
  1691. break;
  1692. }
  1693. }
  1694. }
  1695. }
  1696. /// Check if the existing node-sets are profitable. If not, then ignore the
  1697. /// recurrent node-sets, and attempt to schedule all nodes together. This is
  1698. /// a heuristic. If the MII is large and all the recurrent node-sets are small,
  1699. /// then it's best to try to schedule all instructions together instead of
  1700. /// starting with the recurrent node-sets.
  1701. void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
  1702. // Look for loops with a large MII.
  1703. if (MII < 17)
  1704. return;
  1705. // Check if the node-set contains only a simple add recurrence.
  1706. for (auto &NS : NodeSets) {
  1707. if (NS.getRecMII() > 2)
  1708. return;
  1709. if (NS.getMaxDepth() > MII)
  1710. return;
  1711. }
  1712. NodeSets.clear();
  1713. DEBUG(dbgs() << "Clear recurrence node-sets\n");
  1714. return;
  1715. }
  1716. /// Add the nodes that do not belong to a recurrence set into groups
  1717. /// based upon connected componenets.
  1718. void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
  1719. SetVector<SUnit *> NodesAdded;
  1720. SmallPtrSet<SUnit *, 8> Visited;
  1721. // Add the nodes that are on a path between the previous node sets and
  1722. // the current node set.
  1723. for (NodeSet &I : NodeSets) {
  1724. SmallSetVector<SUnit *, 8> N;
  1725. // Add the nodes from the current node set to the previous node set.
  1726. if (succ_L(I, N)) {
  1727. SetVector<SUnit *> Path;
  1728. for (SUnit *NI : N) {
  1729. Visited.clear();
  1730. computePath(NI, Path, NodesAdded, I, Visited);
  1731. }
  1732. if (!Path.empty())
  1733. I.insert(Path.begin(), Path.end());
  1734. }
  1735. // Add the nodes from the previous node set to the current node set.
  1736. N.clear();
  1737. if (succ_L(NodesAdded, N)) {
  1738. SetVector<SUnit *> Path;
  1739. for (SUnit *NI : N) {
  1740. Visited.clear();
  1741. computePath(NI, Path, I, NodesAdded, Visited);
  1742. }
  1743. if (!Path.empty())
  1744. I.insert(Path.begin(), Path.end());
  1745. }
  1746. NodesAdded.insert(I.begin(), I.end());
  1747. }
  1748. // Create a new node set with the connected nodes of any successor of a node
  1749. // in a recurrent set.
  1750. NodeSet NewSet;
  1751. SmallSetVector<SUnit *, 8> N;
  1752. if (succ_L(NodesAdded, N))
  1753. for (SUnit *I : N)
  1754. addConnectedNodes(I, NewSet, NodesAdded);
  1755. if (!NewSet.empty())
  1756. NodeSets.push_back(NewSet);
  1757. // Create a new node set with the connected nodes of any predecessor of a node
  1758. // in a recurrent set.
  1759. NewSet.clear();
  1760. if (pred_L(NodesAdded, N))
  1761. for (SUnit *I : N)
  1762. addConnectedNodes(I, NewSet, NodesAdded);
  1763. if (!NewSet.empty())
  1764. NodeSets.push_back(NewSet);
  1765. // Create new nodes sets with the connected nodes any remaining node that
  1766. // has no predecessor.
  1767. for (unsigned i = 0; i < SUnits.size(); ++i) {
  1768. SUnit *SU = &SUnits[i];
  1769. if (NodesAdded.count(SU) == 0) {
  1770. NewSet.clear();
  1771. addConnectedNodes(SU, NewSet, NodesAdded);
  1772. if (!NewSet.empty())
  1773. NodeSets.push_back(NewSet);
  1774. }
  1775. }
  1776. }
  1777. /// Add the node to the set, and add all is its connected nodes to the set.
  1778. void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
  1779. SetVector<SUnit *> &NodesAdded) {
  1780. NewSet.insert(SU);
  1781. NodesAdded.insert(SU);
  1782. for (auto &SI : SU->Succs) {
  1783. SUnit *Successor = SI.getSUnit();
  1784. if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
  1785. addConnectedNodes(Successor, NewSet, NodesAdded);
  1786. }
  1787. for (auto &PI : SU->Preds) {
  1788. SUnit *Predecessor = PI.getSUnit();
  1789. if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
  1790. addConnectedNodes(Predecessor, NewSet, NodesAdded);
  1791. }
  1792. }
  1793. /// Return true if Set1 contains elements in Set2. The elements in common
  1794. /// are returned in a different container.
  1795. static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
  1796. SmallSetVector<SUnit *, 8> &Result) {
  1797. Result.clear();
  1798. for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
  1799. SUnit *SU = Set1[i];
  1800. if (Set2.count(SU) != 0)
  1801. Result.insert(SU);
  1802. }
  1803. return !Result.empty();
  1804. }
  1805. /// Merge the recurrence node sets that have the same initial node.
  1806. void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
  1807. for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
  1808. ++I) {
  1809. NodeSet &NI = *I;
  1810. for (NodeSetType::iterator J = I + 1; J != E;) {
  1811. NodeSet &NJ = *J;
  1812. if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
  1813. if (NJ.compareRecMII(NI) > 0)
  1814. NI.setRecMII(NJ.getRecMII());
  1815. for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
  1816. ++NII)
  1817. I->insert(*NII);
  1818. NodeSets.erase(J);
  1819. E = NodeSets.end();
  1820. } else {
  1821. ++J;
  1822. }
  1823. }
  1824. }
  1825. }
  1826. /// Remove nodes that have been scheduled in previous NodeSets.
  1827. void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
  1828. for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
  1829. ++I)
  1830. for (NodeSetType::iterator J = I + 1; J != E;) {
  1831. J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
  1832. if (J->empty()) {
  1833. NodeSets.erase(J);
  1834. E = NodeSets.end();
  1835. } else {
  1836. ++J;
  1837. }
  1838. }
  1839. }
  1840. /// Compute an ordered list of the dependence graph nodes, which
  1841. /// indicates the order that the nodes will be scheduled. This is a
  1842. /// two-level algorithm. First, a partial order is created, which
  1843. /// consists of a list of sets ordered from highest to lowest priority.
  1844. void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
  1845. SmallSetVector<SUnit *, 8> R;
  1846. NodeOrder.clear();
  1847. for (auto &Nodes : NodeSets) {
  1848. DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
  1849. OrderKind Order;
  1850. SmallSetVector<SUnit *, 8> N;
  1851. if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
  1852. R.insert(N.begin(), N.end());
  1853. Order = BottomUp;
  1854. DEBUG(dbgs() << " Bottom up (preds) ");
  1855. } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
  1856. R.insert(N.begin(), N.end());
  1857. Order = TopDown;
  1858. DEBUG(dbgs() << " Top down (succs) ");
  1859. } else if (isIntersect(N, Nodes, R)) {
  1860. // If some of the successors are in the existing node-set, then use the
  1861. // top-down ordering.
  1862. Order = TopDown;
  1863. DEBUG(dbgs() << " Top down (intersect) ");
  1864. } else if (NodeSets.size() == 1) {
  1865. for (auto &N : Nodes)
  1866. if (N->Succs.size() == 0)
  1867. R.insert(N);
  1868. Order = BottomUp;
  1869. DEBUG(dbgs() << " Bottom up (all) ");
  1870. } else {
  1871. // Find the node with the highest ASAP.
  1872. SUnit *maxASAP = nullptr;
  1873. for (SUnit *SU : Nodes) {
  1874. if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
  1875. (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
  1876. maxASAP = SU;
  1877. }
  1878. R.insert(maxASAP);
  1879. Order = BottomUp;
  1880. DEBUG(dbgs() << " Bottom up (default) ");
  1881. }
  1882. while (!R.empty()) {
  1883. if (Order == TopDown) {
  1884. // Choose the node with the maximum height. If more than one, choose
  1885. // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
  1886. // choose the node with the lowest MOV.
  1887. while (!R.empty()) {
  1888. SUnit *maxHeight = nullptr;
  1889. for (SUnit *I : R) {
  1890. if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
  1891. maxHeight = I;
  1892. else if (getHeight(I) == getHeight(maxHeight) &&
  1893. getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
  1894. maxHeight = I;
  1895. else if (getHeight(I) == getHeight(maxHeight) &&
  1896. getZeroLatencyHeight(I) ==
  1897. getZeroLatencyHeight(maxHeight) &&
  1898. getMOV(I) < getMOV(maxHeight))
  1899. maxHeight = I;
  1900. }
  1901. NodeOrder.insert(maxHeight);
  1902. DEBUG(dbgs() << maxHeight->NodeNum << " ");
  1903. R.remove(maxHeight);
  1904. for (const auto &I : maxHeight->Succs) {
  1905. if (Nodes.count(I.getSUnit()) == 0)
  1906. continue;
  1907. if (NodeOrder.count(I.getSUnit()) != 0)
  1908. continue;
  1909. if (ignoreDependence(I, false))
  1910. continue;
  1911. R.insert(I.getSUnit());
  1912. }
  1913. // Back-edges are predecessors with an anti-dependence.
  1914. for (const auto &I : maxHeight->Preds) {
  1915. if (I.getKind() != SDep::Anti)
  1916. continue;
  1917. if (Nodes.count(I.getSUnit()) == 0)
  1918. continue;
  1919. if (NodeOrder.count(I.getSUnit()) != 0)
  1920. continue;
  1921. R.insert(I.getSUnit());
  1922. }
  1923. }
  1924. Order = BottomUp;
  1925. DEBUG(dbgs() << "\n Switching order to bottom up ");
  1926. SmallSetVector<SUnit *, 8> N;
  1927. if (pred_L(NodeOrder, N, &Nodes))
  1928. R.insert(N.begin(), N.end());
  1929. } else {
  1930. // Choose the node with the maximum depth. If more than one, choose
  1931. // the node with the maximum ZeroLatencyDepth. If still more than one,
  1932. // choose the node with the lowest MOV.
  1933. while (!R.empty()) {
  1934. SUnit *maxDepth = nullptr;
  1935. for (SUnit *I : R) {
  1936. if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
  1937. maxDepth = I;
  1938. else if (getDepth(I) == getDepth(maxDepth) &&
  1939. getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
  1940. maxDepth = I;
  1941. else if (getDepth(I) == getDepth(maxDepth) &&
  1942. getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
  1943. getMOV(I) < getMOV(maxDepth))
  1944. maxDepth = I;
  1945. }
  1946. NodeOrder.insert(maxDepth);
  1947. DEBUG(dbgs() << maxDepth->NodeNum << " ");
  1948. R.remove(maxDepth);
  1949. if (Nodes.isExceedSU(maxDepth)) {
  1950. Order = TopDown;
  1951. R.clear();
  1952. R.insert(Nodes.getNode(0));
  1953. break;
  1954. }
  1955. for (const auto &I : maxDepth->Preds) {
  1956. if (Nodes.count(I.getSUnit()) == 0)
  1957. continue;
  1958. if (NodeOrder.count(I.getSUnit()) != 0)
  1959. continue;
  1960. R.insert(I.getSUnit());
  1961. }
  1962. // Back-edges are predecessors with an anti-dependence.
  1963. for (const auto &I : maxDepth->Succs) {
  1964. if (I.getKind() != SDep::Anti)
  1965. continue;
  1966. if (Nodes.count(I.getSUnit()) == 0)
  1967. continue;
  1968. if (NodeOrder.count(I.getSUnit()) != 0)
  1969. continue;
  1970. R.insert(I.getSUnit());
  1971. }
  1972. }
  1973. Order = TopDown;
  1974. DEBUG(dbgs() << "\n Switching order to top down ");
  1975. SmallSetVector<SUnit *, 8> N;
  1976. if (succ_L(NodeOrder, N, &Nodes))
  1977. R.insert(N.begin(), N.end());
  1978. }
  1979. }
  1980. DEBUG(dbgs() << "\nDone with Nodeset\n");
  1981. }
  1982. DEBUG({
  1983. dbgs() << "Node order: ";
  1984. for (SUnit *I : NodeOrder)
  1985. dbgs() << " " << I->NodeNum << " ";
  1986. dbgs() << "\n";
  1987. });
  1988. }
  1989. /// Process the nodes in the computed order and create the pipelined schedule
  1990. /// of the instructions, if possible. Return true if a schedule is found.
  1991. bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
  1992. if (NodeOrder.empty())
  1993. return false;
  1994. bool scheduleFound = false;
  1995. // Keep increasing II until a valid schedule is found.
  1996. for (unsigned II = MII; II < MII + 10 && !scheduleFound; ++II) {
  1997. Schedule.reset();
  1998. Schedule.setInitiationInterval(II);
  1999. DEBUG(dbgs() << "Try to schedule with " << II << "\n");
  2000. SetVector<SUnit *>::iterator NI = NodeOrder.begin();
  2001. SetVector<SUnit *>::iterator NE = NodeOrder.end();
  2002. do {
  2003. SUnit *SU = *NI;
  2004. // Compute the schedule time for the instruction, which is based
  2005. // upon the scheduled time for any predecessors/successors.
  2006. int EarlyStart = INT_MIN;
  2007. int LateStart = INT_MAX;
  2008. // These values are set when the size of the schedule window is limited
  2009. // due to chain dependences.
  2010. int SchedEnd = INT_MAX;
  2011. int SchedStart = INT_MIN;
  2012. Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
  2013. II, this);
  2014. DEBUG({
  2015. dbgs() << "Inst (" << SU->NodeNum << ") ";
  2016. SU->getInstr()->dump();
  2017. dbgs() << "\n";
  2018. });
  2019. DEBUG({
  2020. dbgs() << "\tes: " << EarlyStart << " ls: " << LateStart
  2021. << " me: " << SchedEnd << " ms: " << SchedStart << "\n";
  2022. });
  2023. if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
  2024. SchedStart > LateStart)
  2025. scheduleFound = false;
  2026. else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
  2027. SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
  2028. scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
  2029. } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
  2030. SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
  2031. scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
  2032. } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
  2033. SchedEnd =
  2034. std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
  2035. // When scheduling a Phi it is better to start at the late cycle and go
  2036. // backwards. The default order may insert the Phi too far away from
  2037. // its first dependence.
  2038. if (SU->getInstr()->isPHI())
  2039. scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
  2040. else
  2041. scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
  2042. } else {
  2043. int FirstCycle = Schedule.getFirstCycle();
  2044. scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
  2045. FirstCycle + getASAP(SU) + II - 1, II);
  2046. }
  2047. // Even if we find a schedule, make sure the schedule doesn't exceed the
  2048. // allowable number of stages. We keep trying if this happens.
  2049. if (scheduleFound)
  2050. if (SwpMaxStages > -1 &&
  2051. Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
  2052. scheduleFound = false;
  2053. DEBUG({
  2054. if (!scheduleFound)
  2055. dbgs() << "\tCan't schedule\n";
  2056. });
  2057. } while (++NI != NE && scheduleFound);
  2058. // If a schedule is found, check if it is a valid schedule too.
  2059. if (scheduleFound)
  2060. scheduleFound = Schedule.isValidSchedule(this);
  2061. }
  2062. DEBUG(dbgs() << "Schedule Found? " << scheduleFound << "\n");
  2063. if (scheduleFound)
  2064. Schedule.finalizeSchedule(this);
  2065. else
  2066. Schedule.reset();
  2067. return scheduleFound && Schedule.getMaxStageCount() > 0;
  2068. }
  2069. /// Given a schedule for the loop, generate a new version of the loop,
  2070. /// and replace the old version. This function generates a prolog
  2071. /// that contains the initial iterations in the pipeline, and kernel
  2072. /// loop, and the epilogue that contains the code for the final
  2073. /// iterations.
  2074. void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
  2075. // Create a new basic block for the kernel and add it to the CFG.
  2076. MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
  2077. unsigned MaxStageCount = Schedule.getMaxStageCount();
  2078. // Remember the registers that are used in different stages. The index is
  2079. // the iteration, or stage, that the instruction is scheduled in. This is
  2080. // a map between register names in the orignal block and the names created
  2081. // in each stage of the pipelined loop.
  2082. ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
  2083. InstrMapTy InstrMap;
  2084. SmallVector<MachineBasicBlock *, 4> PrologBBs;
  2085. // Generate the prolog instructions that set up the pipeline.
  2086. generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
  2087. MF.insert(BB->getIterator(), KernelBB);
  2088. // Rearrange the instructions to generate the new, pipelined loop,
  2089. // and update register names as needed.
  2090. for (int Cycle = Schedule.getFirstCycle(),
  2091. LastCycle = Schedule.getFinalCycle();
  2092. Cycle <= LastCycle; ++Cycle) {
  2093. std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
  2094. // This inner loop schedules each instruction in the cycle.
  2095. for (SUnit *CI : CycleInstrs) {
  2096. if (CI->getInstr()->isPHI())
  2097. continue;
  2098. unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
  2099. MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
  2100. updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
  2101. KernelBB->push_back(NewMI);
  2102. InstrMap[NewMI] = CI->getInstr();
  2103. }
  2104. }
  2105. // Copy any terminator instructions to the new kernel, and update
  2106. // names as needed.
  2107. for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
  2108. E = BB->instr_end();
  2109. I != E; ++I) {
  2110. MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
  2111. updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
  2112. KernelBB->push_back(NewMI);
  2113. InstrMap[NewMI] = &*I;
  2114. }
  2115. KernelBB->transferSuccessors(BB);
  2116. KernelBB->replaceSuccessor(BB, KernelBB);
  2117. generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
  2118. VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
  2119. generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
  2120. InstrMap, MaxStageCount, MaxStageCount, false);
  2121. DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
  2122. SmallVector<MachineBasicBlock *, 4> EpilogBBs;
  2123. // Generate the epilog instructions to complete the pipeline.
  2124. generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
  2125. PrologBBs);
  2126. // We need this step because the register allocation doesn't handle some
  2127. // situations well, so we insert copies to help out.
  2128. splitLifetimes(KernelBB, EpilogBBs, Schedule);
  2129. // Remove dead instructions due to loop induction variables.
  2130. removeDeadInstructions(KernelBB, EpilogBBs);
  2131. // Add branches between prolog and epilog blocks.
  2132. addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
  2133. // Remove the original loop since it's no longer referenced.
  2134. for (auto &I : *BB)
  2135. LIS.RemoveMachineInstrFromMaps(I);
  2136. BB->clear();
  2137. BB->eraseFromParent();
  2138. delete[] VRMap;
  2139. }
  2140. /// Generate the pipeline prolog code.
  2141. void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
  2142. MachineBasicBlock *KernelBB,
  2143. ValueMapTy *VRMap,
  2144. MBBVectorTy &PrologBBs) {
  2145. MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
  2146. assert(PreheaderBB != nullptr &&
  2147. "Need to add code to handle loops w/o preheader");
  2148. MachineBasicBlock *PredBB = PreheaderBB;
  2149. InstrMapTy InstrMap;
  2150. // Generate a basic block for each stage, not including the last stage,
  2151. // which will be generated in the kernel. Each basic block may contain
  2152. // instructions from multiple stages/iterations.
  2153. for (unsigned i = 0; i < LastStage; ++i) {
  2154. // Create and insert the prolog basic block prior to the original loop
  2155. // basic block. The original loop is removed later.
  2156. MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
  2157. PrologBBs.push_back(NewBB);
  2158. MF.insert(BB->getIterator(), NewBB);
  2159. NewBB->transferSuccessors(PredBB);
  2160. PredBB->addSuccessor(NewBB);
  2161. PredBB = NewBB;
  2162. // Generate instructions for each appropriate stage. Process instructions
  2163. // in original program order.
  2164. for (int StageNum = i; StageNum >= 0; --StageNum) {
  2165. for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
  2166. BBE = BB->getFirstTerminator();
  2167. BBI != BBE; ++BBI) {
  2168. if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
  2169. if (BBI->isPHI())
  2170. continue;
  2171. MachineInstr *NewMI =
  2172. cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
  2173. updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
  2174. VRMap);
  2175. NewBB->push_back(NewMI);
  2176. InstrMap[NewMI] = &*BBI;
  2177. }
  2178. }
  2179. }
  2180. rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
  2181. DEBUG({
  2182. dbgs() << "prolog:\n";
  2183. NewBB->dump();
  2184. });
  2185. }
  2186. PredBB->replaceSuccessor(BB, KernelBB);
  2187. // Check if we need to remove the branch from the preheader to the original
  2188. // loop, and replace it with a branch to the new loop.
  2189. unsigned numBranches = TII->removeBranch(*PreheaderBB);
  2190. if (numBranches) {
  2191. SmallVector<MachineOperand, 0> Cond;
  2192. TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
  2193. }
  2194. }
  2195. /// Generate the pipeline epilog code. The epilog code finishes the iterations
  2196. /// that were started in either the prolog or the kernel. We create a basic
  2197. /// block for each stage that needs to complete.
  2198. void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
  2199. MachineBasicBlock *KernelBB,
  2200. ValueMapTy *VRMap,
  2201. MBBVectorTy &EpilogBBs,
  2202. MBBVectorTy &PrologBBs) {
  2203. // We need to change the branch from the kernel to the first epilog block, so
  2204. // this call to analyze branch uses the kernel rather than the original BB.
  2205. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  2206. SmallVector<MachineOperand, 4> Cond;
  2207. bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
  2208. assert(!checkBranch && "generateEpilog must be able to analyze the branch");
  2209. if (checkBranch)
  2210. return;
  2211. MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
  2212. if (*LoopExitI == KernelBB)
  2213. ++LoopExitI;
  2214. assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
  2215. MachineBasicBlock *LoopExitBB = *LoopExitI;
  2216. MachineBasicBlock *PredBB = KernelBB;
  2217. MachineBasicBlock *EpilogStart = LoopExitBB;
  2218. InstrMapTy InstrMap;
  2219. // Generate a basic block for each stage, not including the last stage,
  2220. // which was generated for the kernel. Each basic block may contain
  2221. // instructions from multiple stages/iterations.
  2222. int EpilogStage = LastStage + 1;
  2223. for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
  2224. MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
  2225. EpilogBBs.push_back(NewBB);
  2226. MF.insert(BB->getIterator(), NewBB);
  2227. PredBB->replaceSuccessor(LoopExitBB, NewBB);
  2228. NewBB->addSuccessor(LoopExitBB);
  2229. if (EpilogStart == LoopExitBB)
  2230. EpilogStart = NewBB;
  2231. // Add instructions to the epilog depending on the current block.
  2232. // Process instructions in original program order.
  2233. for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
  2234. for (auto &BBI : *BB) {
  2235. if (BBI.isPHI())
  2236. continue;
  2237. MachineInstr *In = &BBI;
  2238. if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
  2239. // Instructions with memoperands in the epilog are updated with
  2240. // conservative values.
  2241. MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
  2242. updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
  2243. NewBB->push_back(NewMI);
  2244. InstrMap[NewMI] = In;
  2245. }
  2246. }
  2247. }
  2248. generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
  2249. VRMap, InstrMap, LastStage, EpilogStage, i == 1);
  2250. generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
  2251. InstrMap, LastStage, EpilogStage, i == 1);
  2252. PredBB = NewBB;
  2253. DEBUG({
  2254. dbgs() << "epilog:\n";
  2255. NewBB->dump();
  2256. });
  2257. }
  2258. // Fix any Phi nodes in the loop exit block.
  2259. for (MachineInstr &MI : *LoopExitBB) {
  2260. if (!MI.isPHI())
  2261. break;
  2262. for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
  2263. MachineOperand &MO = MI.getOperand(i);
  2264. if (MO.getMBB() == BB)
  2265. MO.setMBB(PredBB);
  2266. }
  2267. }
  2268. // Create a branch to the new epilog from the kernel.
  2269. // Remove the original branch and add a new branch to the epilog.
  2270. TII->removeBranch(*KernelBB);
  2271. TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
  2272. // Add a branch to the loop exit.
  2273. if (EpilogBBs.size() > 0) {
  2274. MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
  2275. SmallVector<MachineOperand, 4> Cond1;
  2276. TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
  2277. }
  2278. }
  2279. /// Replace all uses of FromReg that appear outside the specified
  2280. /// basic block with ToReg.
  2281. static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
  2282. MachineBasicBlock *MBB,
  2283. MachineRegisterInfo &MRI,
  2284. LiveIntervals &LIS) {
  2285. for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
  2286. E = MRI.use_end();
  2287. I != E;) {
  2288. MachineOperand &O = *I;
  2289. ++I;
  2290. if (O.getParent()->getParent() != MBB)
  2291. O.setReg(ToReg);
  2292. }
  2293. if (!LIS.hasInterval(ToReg))
  2294. LIS.createEmptyInterval(ToReg);
  2295. }
  2296. /// Return true if the register has a use that occurs outside the
  2297. /// specified loop.
  2298. static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
  2299. MachineRegisterInfo &MRI) {
  2300. for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
  2301. E = MRI.use_end();
  2302. I != E; ++I)
  2303. if (I->getParent()->getParent() != BB)
  2304. return true;
  2305. return false;
  2306. }
  2307. /// Generate Phis for the specific block in the generated pipelined code.
  2308. /// This function looks at the Phis from the original code to guide the
  2309. /// creation of new Phis.
  2310. void SwingSchedulerDAG::generateExistingPhis(
  2311. MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
  2312. MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
  2313. InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
  2314. bool IsLast) {
  2315. // Compute the stage number for the initial value of the Phi, which
  2316. // comes from the prolog. The prolog to use depends on to which kernel/
  2317. // epilog that we're adding the Phi.
  2318. unsigned PrologStage = 0;
  2319. unsigned PrevStage = 0;
  2320. bool InKernel = (LastStageNum == CurStageNum);
  2321. if (InKernel) {
  2322. PrologStage = LastStageNum - 1;
  2323. PrevStage = CurStageNum;
  2324. } else {
  2325. PrologStage = LastStageNum - (CurStageNum - LastStageNum);
  2326. PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
  2327. }
  2328. for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
  2329. BBE = BB->getFirstNonPHI();
  2330. BBI != BBE; ++BBI) {
  2331. unsigned Def = BBI->getOperand(0).getReg();
  2332. unsigned InitVal = 0;
  2333. unsigned LoopVal = 0;
  2334. getPhiRegs(*BBI, BB, InitVal, LoopVal);
  2335. unsigned PhiOp1 = 0;
  2336. // The Phi value from the loop body typically is defined in the loop, but
  2337. // not always. So, we need to check if the value is defined in the loop.
  2338. unsigned PhiOp2 = LoopVal;
  2339. if (VRMap[LastStageNum].count(LoopVal))
  2340. PhiOp2 = VRMap[LastStageNum][LoopVal];
  2341. int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
  2342. int LoopValStage =
  2343. Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
  2344. unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
  2345. if (NumStages == 0) {
  2346. // We don't need to generate a Phi anymore, but we need to rename any uses
  2347. // of the Phi value.
  2348. unsigned NewReg = VRMap[PrevStage][LoopVal];
  2349. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
  2350. Def, InitVal, NewReg);
  2351. if (VRMap[CurStageNum].count(LoopVal))
  2352. VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
  2353. }
  2354. // Adjust the number of Phis needed depending on the number of prologs left,
  2355. // and the distance from where the Phi is first scheduled. The number of
  2356. // Phis cannot exceed the number of prolog stages. Each stage can
  2357. // potentially define two values.
  2358. unsigned MaxPhis = PrologStage + 2;
  2359. if (!InKernel && (int)PrologStage <= LoopValStage)
  2360. MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
  2361. unsigned NumPhis = std::min(NumStages, MaxPhis);
  2362. unsigned NewReg = 0;
  2363. unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
  2364. // In the epilog, we may need to look back one stage to get the correct
  2365. // Phi name because the epilog and prolog blocks execute the same stage.
  2366. // The correct name is from the previous block only when the Phi has
  2367. // been completely scheduled prior to the epilog, and Phi value is not
  2368. // needed in multiple stages.
  2369. int StageDiff = 0;
  2370. if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
  2371. NumPhis == 1)
  2372. StageDiff = 1;
  2373. // Adjust the computations below when the phi and the loop definition
  2374. // are scheduled in different stages.
  2375. if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
  2376. StageDiff = StageScheduled - LoopValStage;
  2377. for (unsigned np = 0; np < NumPhis; ++np) {
  2378. // If the Phi hasn't been scheduled, then use the initial Phi operand
  2379. // value. Otherwise, use the scheduled version of the instruction. This
  2380. // is a little complicated when a Phi references another Phi.
  2381. if (np > PrologStage || StageScheduled >= (int)LastStageNum)
  2382. PhiOp1 = InitVal;
  2383. // Check if the Phi has already been scheduled in a prolog stage.
  2384. else if (PrologStage >= AccessStage + StageDiff + np &&
  2385. VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
  2386. PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
  2387. // Check if the Phi has already been scheduled, but the loop intruction
  2388. // is either another Phi, or doesn't occur in the loop.
  2389. else if (PrologStage >= AccessStage + StageDiff + np) {
  2390. // If the Phi references another Phi, we need to examine the other
  2391. // Phi to get the correct value.
  2392. PhiOp1 = LoopVal;
  2393. MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
  2394. int Indirects = 1;
  2395. while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
  2396. int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
  2397. if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
  2398. PhiOp1 = getInitPhiReg(*InstOp1, BB);
  2399. else
  2400. PhiOp1 = getLoopPhiReg(*InstOp1, BB);
  2401. InstOp1 = MRI.getVRegDef(PhiOp1);
  2402. int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
  2403. int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
  2404. if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
  2405. VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
  2406. PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
  2407. break;
  2408. }
  2409. ++Indirects;
  2410. }
  2411. } else
  2412. PhiOp1 = InitVal;
  2413. // If this references a generated Phi in the kernel, get the Phi operand
  2414. // from the incoming block.
  2415. if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
  2416. if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
  2417. PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
  2418. MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
  2419. bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
  2420. // In the epilog, a map lookup is needed to get the value from the kernel,
  2421. // or previous epilog block. How is does this depends on if the
  2422. // instruction is scheduled in the previous block.
  2423. if (!InKernel) {
  2424. int StageDiffAdj = 0;
  2425. if (LoopValStage != -1 && StageScheduled > LoopValStage)
  2426. StageDiffAdj = StageScheduled - LoopValStage;
  2427. // Use the loop value defined in the kernel, unless the kernel
  2428. // contains the last definition of the Phi.
  2429. if (np == 0 && PrevStage == LastStageNum &&
  2430. (StageScheduled != 0 || LoopValStage != 0) &&
  2431. VRMap[PrevStage - StageDiffAdj].count(LoopVal))
  2432. PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
  2433. // Use the value defined by the Phi. We add one because we switch
  2434. // from looking at the loop value to the Phi definition.
  2435. else if (np > 0 && PrevStage == LastStageNum &&
  2436. VRMap[PrevStage - np + 1].count(Def))
  2437. PhiOp2 = VRMap[PrevStage - np + 1][Def];
  2438. // Use the loop value defined in the kernel.
  2439. else if ((unsigned)LoopValStage + StageDiffAdj > PrologStage + 1 &&
  2440. VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
  2441. PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
  2442. // Use the value defined by the Phi, unless we're generating the first
  2443. // epilog and the Phi refers to a Phi in a different stage.
  2444. else if (VRMap[PrevStage - np].count(Def) &&
  2445. (!LoopDefIsPhi || PrevStage != LastStageNum))
  2446. PhiOp2 = VRMap[PrevStage - np][Def];
  2447. }
  2448. // Check if we can reuse an existing Phi. This occurs when a Phi
  2449. // references another Phi, and the other Phi is scheduled in an
  2450. // earlier stage. We can try to reuse an existing Phi up until the last
  2451. // stage of the current Phi.
  2452. if (LoopDefIsPhi && (int)(PrologStage - np) >= StageScheduled) {
  2453. int LVNumStages = Schedule.getStagesForPhi(LoopVal);
  2454. int StageDiff = (StageScheduled - LoopValStage);
  2455. LVNumStages -= StageDiff;
  2456. // Make sure the loop value Phi has been processed already.
  2457. if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
  2458. NewReg = PhiOp2;
  2459. unsigned ReuseStage = CurStageNum;
  2460. if (Schedule.isLoopCarried(this, *PhiInst))
  2461. ReuseStage -= LVNumStages;
  2462. // Check if the Phi to reuse has been generated yet. If not, then
  2463. // there is nothing to reuse.
  2464. if (VRMap[ReuseStage - np].count(LoopVal)) {
  2465. NewReg = VRMap[ReuseStage - np][LoopVal];
  2466. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2467. &*BBI, Def, NewReg);
  2468. // Update the map with the new Phi name.
  2469. VRMap[CurStageNum - np][Def] = NewReg;
  2470. PhiOp2 = NewReg;
  2471. if (VRMap[LastStageNum - np - 1].count(LoopVal))
  2472. PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
  2473. if (IsLast && np == NumPhis - 1)
  2474. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  2475. continue;
  2476. }
  2477. } else if (InKernel && StageDiff > 0 &&
  2478. VRMap[CurStageNum - StageDiff - np].count(LoopVal))
  2479. PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
  2480. }
  2481. const TargetRegisterClass *RC = MRI.getRegClass(Def);
  2482. NewReg = MRI.createVirtualRegister(RC);
  2483. MachineInstrBuilder NewPhi =
  2484. BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
  2485. TII->get(TargetOpcode::PHI), NewReg);
  2486. NewPhi.addReg(PhiOp1).addMBB(BB1);
  2487. NewPhi.addReg(PhiOp2).addMBB(BB2);
  2488. if (np == 0)
  2489. InstrMap[NewPhi] = &*BBI;
  2490. // We define the Phis after creating the new pipelined code, so
  2491. // we need to rename the Phi values in scheduled instructions.
  2492. unsigned PrevReg = 0;
  2493. if (InKernel && VRMap[PrevStage - np].count(LoopVal))
  2494. PrevReg = VRMap[PrevStage - np][LoopVal];
  2495. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
  2496. Def, NewReg, PrevReg);
  2497. // If the Phi has been scheduled, use the new name for rewriting.
  2498. if (VRMap[CurStageNum - np].count(Def)) {
  2499. unsigned R = VRMap[CurStageNum - np][Def];
  2500. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
  2501. R, NewReg);
  2502. }
  2503. // Check if we need to rename any uses that occurs after the loop. The
  2504. // register to replace depends on whether the Phi is scheduled in the
  2505. // epilog.
  2506. if (IsLast && np == NumPhis - 1)
  2507. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  2508. // In the kernel, a dependent Phi uses the value from this Phi.
  2509. if (InKernel)
  2510. PhiOp2 = NewReg;
  2511. // Update the map with the new Phi name.
  2512. VRMap[CurStageNum - np][Def] = NewReg;
  2513. }
  2514. while (NumPhis++ < NumStages) {
  2515. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
  2516. &*BBI, Def, NewReg, 0);
  2517. }
  2518. // Check if we need to rename a Phi that has been eliminated due to
  2519. // scheduling.
  2520. if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
  2521. replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
  2522. }
  2523. }
  2524. /// Generate Phis for the specified block in the generated pipelined code.
  2525. /// These are new Phis needed because the definition is scheduled after the
  2526. /// use in the pipelened sequence.
  2527. void SwingSchedulerDAG::generatePhis(
  2528. MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
  2529. MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
  2530. InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
  2531. bool IsLast) {
  2532. // Compute the stage number that contains the initial Phi value, and
  2533. // the Phi from the previous stage.
  2534. unsigned PrologStage = 0;
  2535. unsigned PrevStage = 0;
  2536. unsigned StageDiff = CurStageNum - LastStageNum;
  2537. bool InKernel = (StageDiff == 0);
  2538. if (InKernel) {
  2539. PrologStage = LastStageNum - 1;
  2540. PrevStage = CurStageNum;
  2541. } else {
  2542. PrologStage = LastStageNum - StageDiff;
  2543. PrevStage = LastStageNum + StageDiff - 1;
  2544. }
  2545. for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
  2546. BBE = BB->instr_end();
  2547. BBI != BBE; ++BBI) {
  2548. for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
  2549. MachineOperand &MO = BBI->getOperand(i);
  2550. if (!MO.isReg() || !MO.isDef() ||
  2551. !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  2552. continue;
  2553. int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
  2554. assert(StageScheduled != -1 && "Expecting scheduled instruction.");
  2555. unsigned Def = MO.getReg();
  2556. unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
  2557. // An instruction scheduled in stage 0 and is used after the loop
  2558. // requires a phi in the epilog for the last definition from either
  2559. // the kernel or prolog.
  2560. if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
  2561. hasUseAfterLoop(Def, BB, MRI))
  2562. NumPhis = 1;
  2563. if (!InKernel && (unsigned)StageScheduled > PrologStage)
  2564. continue;
  2565. unsigned PhiOp2 = VRMap[PrevStage][Def];
  2566. if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
  2567. if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
  2568. PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
  2569. // The number of Phis can't exceed the number of prolog stages. The
  2570. // prolog stage number is zero based.
  2571. if (NumPhis > PrologStage + 1 - StageScheduled)
  2572. NumPhis = PrologStage + 1 - StageScheduled;
  2573. for (unsigned np = 0; np < NumPhis; ++np) {
  2574. unsigned PhiOp1 = VRMap[PrologStage][Def];
  2575. if (np <= PrologStage)
  2576. PhiOp1 = VRMap[PrologStage - np][Def];
  2577. if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
  2578. if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
  2579. PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
  2580. if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
  2581. PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
  2582. }
  2583. if (!InKernel)
  2584. PhiOp2 = VRMap[PrevStage - np][Def];
  2585. const TargetRegisterClass *RC = MRI.getRegClass(Def);
  2586. unsigned NewReg = MRI.createVirtualRegister(RC);
  2587. MachineInstrBuilder NewPhi =
  2588. BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
  2589. TII->get(TargetOpcode::PHI), NewReg);
  2590. NewPhi.addReg(PhiOp1).addMBB(BB1);
  2591. NewPhi.addReg(PhiOp2).addMBB(BB2);
  2592. if (np == 0)
  2593. InstrMap[NewPhi] = &*BBI;
  2594. // Rewrite uses and update the map. The actions depend upon whether
  2595. // we generating code for the kernel or epilog blocks.
  2596. if (InKernel) {
  2597. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2598. &*BBI, PhiOp1, NewReg);
  2599. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2600. &*BBI, PhiOp2, NewReg);
  2601. PhiOp2 = NewReg;
  2602. VRMap[PrevStage - np - 1][Def] = NewReg;
  2603. } else {
  2604. VRMap[CurStageNum - np][Def] = NewReg;
  2605. if (np == NumPhis - 1)
  2606. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2607. &*BBI, Def, NewReg);
  2608. }
  2609. if (IsLast && np == NumPhis - 1)
  2610. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  2611. }
  2612. }
  2613. }
  2614. }
  2615. /// Remove instructions that generate values with no uses.
  2616. /// Typically, these are induction variable operations that generate values
  2617. /// used in the loop itself. A dead instruction has a definition with
  2618. /// no uses, or uses that occur in the original loop only.
  2619. void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
  2620. MBBVectorTy &EpilogBBs) {
  2621. // For each epilog block, check that the value defined by each instruction
  2622. // is used. If not, delete it.
  2623. for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
  2624. MBE = EpilogBBs.rend();
  2625. MBB != MBE; ++MBB)
  2626. for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
  2627. ME = (*MBB)->instr_rend();
  2628. MI != ME;) {
  2629. // From DeadMachineInstructionElem. Don't delete inline assembly.
  2630. if (MI->isInlineAsm()) {
  2631. ++MI;
  2632. continue;
  2633. }
  2634. bool SawStore = false;
  2635. // Check if it's safe to remove the instruction due to side effects.
  2636. // We can, and want to, remove Phis here.
  2637. if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
  2638. ++MI;
  2639. continue;
  2640. }
  2641. bool used = true;
  2642. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  2643. MOE = MI->operands_end();
  2644. MOI != MOE; ++MOI) {
  2645. if (!MOI->isReg() || !MOI->isDef())
  2646. continue;
  2647. unsigned reg = MOI->getReg();
  2648. // Assume physical registers are used, unless they are marked dead.
  2649. if (TargetRegisterInfo::isPhysicalRegister(reg)) {
  2650. used = !MOI->isDead();
  2651. if (used)
  2652. break;
  2653. continue;
  2654. }
  2655. unsigned realUses = 0;
  2656. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
  2657. EI = MRI.use_end();
  2658. UI != EI; ++UI) {
  2659. // Check if there are any uses that occur only in the original
  2660. // loop. If so, that's not a real use.
  2661. if (UI->getParent()->getParent() != BB) {
  2662. realUses++;
  2663. used = true;
  2664. break;
  2665. }
  2666. }
  2667. if (realUses > 0)
  2668. break;
  2669. used = false;
  2670. }
  2671. if (!used) {
  2672. LIS.RemoveMachineInstrFromMaps(*MI);
  2673. MI++->eraseFromParent();
  2674. continue;
  2675. }
  2676. ++MI;
  2677. }
  2678. // In the kernel block, check if we can remove a Phi that generates a value
  2679. // used in an instruction removed in the epilog block.
  2680. for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
  2681. BBE = KernelBB->getFirstNonPHI();
  2682. BBI != BBE;) {
  2683. MachineInstr *MI = &*BBI;
  2684. ++BBI;
  2685. unsigned reg = MI->getOperand(0).getReg();
  2686. if (MRI.use_begin(reg) == MRI.use_end()) {
  2687. LIS.RemoveMachineInstrFromMaps(*MI);
  2688. MI->eraseFromParent();
  2689. }
  2690. }
  2691. }
  2692. /// For loop carried definitions, we split the lifetime of a virtual register
  2693. /// that has uses past the definition in the next iteration. A copy with a new
  2694. /// virtual register is inserted before the definition, which helps with
  2695. /// generating a better register assignment.
  2696. ///
  2697. /// v1 = phi(a, v2) v1 = phi(a, v2)
  2698. /// v2 = phi(b, v3) v2 = phi(b, v3)
  2699. /// v3 = .. v4 = copy v1
  2700. /// .. = V1 v3 = ..
  2701. /// .. = v4
  2702. void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
  2703. MBBVectorTy &EpilogBBs,
  2704. SMSchedule &Schedule) {
  2705. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2706. for (auto &PHI : KernelBB->phis()) {
  2707. unsigned Def = PHI.getOperand(0).getReg();
  2708. // Check for any Phi definition that used as an operand of another Phi
  2709. // in the same block.
  2710. for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
  2711. E = MRI.use_instr_end();
  2712. I != E; ++I) {
  2713. if (I->isPHI() && I->getParent() == KernelBB) {
  2714. // Get the loop carried definition.
  2715. unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
  2716. if (!LCDef)
  2717. continue;
  2718. MachineInstr *MI = MRI.getVRegDef(LCDef);
  2719. if (!MI || MI->getParent() != KernelBB || MI->isPHI())
  2720. continue;
  2721. // Search through the rest of the block looking for uses of the Phi
  2722. // definition. If one occurs, then split the lifetime.
  2723. unsigned SplitReg = 0;
  2724. for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
  2725. KernelBB->instr_end()))
  2726. if (BBJ.readsRegister(Def)) {
  2727. // We split the lifetime when we find the first use.
  2728. if (SplitReg == 0) {
  2729. SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
  2730. BuildMI(*KernelBB, MI, MI->getDebugLoc(),
  2731. TII->get(TargetOpcode::COPY), SplitReg)
  2732. .addReg(Def);
  2733. }
  2734. BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
  2735. }
  2736. if (!SplitReg)
  2737. continue;
  2738. // Search through each of the epilog blocks for any uses to be renamed.
  2739. for (auto &Epilog : EpilogBBs)
  2740. for (auto &I : *Epilog)
  2741. if (I.readsRegister(Def))
  2742. I.substituteRegister(Def, SplitReg, 0, *TRI);
  2743. break;
  2744. }
  2745. }
  2746. }
  2747. }
  2748. /// Remove the incoming block from the Phis in a basic block.
  2749. static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
  2750. for (MachineInstr &MI : *BB) {
  2751. if (!MI.isPHI())
  2752. break;
  2753. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
  2754. if (MI.getOperand(i + 1).getMBB() == Incoming) {
  2755. MI.RemoveOperand(i + 1);
  2756. MI.RemoveOperand(i);
  2757. break;
  2758. }
  2759. }
  2760. }
  2761. /// Create branches from each prolog basic block to the appropriate epilog
  2762. /// block. These edges are needed if the loop ends before reaching the
  2763. /// kernel.
  2764. void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs,
  2765. MachineBasicBlock *KernelBB,
  2766. MBBVectorTy &EpilogBBs,
  2767. SMSchedule &Schedule, ValueMapTy *VRMap) {
  2768. assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
  2769. MachineInstr *IndVar = Pass.LI.LoopInductionVar;
  2770. MachineInstr *Cmp = Pass.LI.LoopCompare;
  2771. MachineBasicBlock *LastPro = KernelBB;
  2772. MachineBasicBlock *LastEpi = KernelBB;
  2773. // Start from the blocks connected to the kernel and work "out"
  2774. // to the first prolog and the last epilog blocks.
  2775. SmallVector<MachineInstr *, 4> PrevInsts;
  2776. unsigned MaxIter = PrologBBs.size() - 1;
  2777. unsigned LC = UINT_MAX;
  2778. unsigned LCMin = UINT_MAX;
  2779. for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
  2780. // Add branches to the prolog that go to the corresponding
  2781. // epilog, and the fall-thru prolog/kernel block.
  2782. MachineBasicBlock *Prolog = PrologBBs[j];
  2783. MachineBasicBlock *Epilog = EpilogBBs[i];
  2784. // We've executed one iteration, so decrement the loop count and check for
  2785. // the loop end.
  2786. SmallVector<MachineOperand, 4> Cond;
  2787. // Check if the LOOP0 has already been removed. If so, then there is no need
  2788. // to reduce the trip count.
  2789. if (LC != 0)
  2790. LC = TII->reduceLoopCount(*Prolog, IndVar, *Cmp, Cond, PrevInsts, j,
  2791. MaxIter);
  2792. // Record the value of the first trip count, which is used to determine if
  2793. // branches and blocks can be removed for constant trip counts.
  2794. if (LCMin == UINT_MAX)
  2795. LCMin = LC;
  2796. unsigned numAdded = 0;
  2797. if (TargetRegisterInfo::isVirtualRegister(LC)) {
  2798. Prolog->addSuccessor(Epilog);
  2799. numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
  2800. } else if (j >= LCMin) {
  2801. Prolog->addSuccessor(Epilog);
  2802. Prolog->removeSuccessor(LastPro);
  2803. LastEpi->removeSuccessor(Epilog);
  2804. numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
  2805. removePhis(Epilog, LastEpi);
  2806. // Remove the blocks that are no longer referenced.
  2807. if (LastPro != LastEpi) {
  2808. LastEpi->clear();
  2809. LastEpi->eraseFromParent();
  2810. }
  2811. LastPro->clear();
  2812. LastPro->eraseFromParent();
  2813. } else {
  2814. numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
  2815. removePhis(Epilog, Prolog);
  2816. }
  2817. LastPro = Prolog;
  2818. LastEpi = Epilog;
  2819. for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
  2820. E = Prolog->instr_rend();
  2821. I != E && numAdded > 0; ++I, --numAdded)
  2822. updateInstruction(&*I, false, j, 0, Schedule, VRMap);
  2823. }
  2824. }
  2825. /// Return true if we can compute the amount the instruction changes
  2826. /// during each iteration. Set Delta to the amount of the change.
  2827. bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
  2828. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2829. unsigned BaseReg;
  2830. int64_t Offset;
  2831. if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
  2832. return false;
  2833. MachineRegisterInfo &MRI = MF.getRegInfo();
  2834. // Check if there is a Phi. If so, get the definition in the loop.
  2835. MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
  2836. if (BaseDef && BaseDef->isPHI()) {
  2837. BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
  2838. BaseDef = MRI.getVRegDef(BaseReg);
  2839. }
  2840. if (!BaseDef)
  2841. return false;
  2842. int D = 0;
  2843. if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
  2844. return false;
  2845. Delta = D;
  2846. return true;
  2847. }
  2848. /// Update the memory operand with a new offset when the pipeliner
  2849. /// generates a new copy of the instruction that refers to a
  2850. /// different memory location.
  2851. void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
  2852. MachineInstr &OldMI, unsigned Num) {
  2853. if (Num == 0)
  2854. return;
  2855. // If the instruction has memory operands, then adjust the offset
  2856. // when the instruction appears in different stages.
  2857. unsigned NumRefs = NewMI.memoperands_end() - NewMI.memoperands_begin();
  2858. if (NumRefs == 0)
  2859. return;
  2860. MachineInstr::mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NumRefs);
  2861. unsigned Refs = 0;
  2862. for (MachineMemOperand *MMO : NewMI.memoperands()) {
  2863. if (MMO->isVolatile() || (MMO->isInvariant() && MMO->isDereferenceable()) ||
  2864. (!MMO->getValue())) {
  2865. NewMemRefs[Refs++] = MMO;
  2866. continue;
  2867. }
  2868. unsigned Delta;
  2869. if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
  2870. int64_t AdjOffset = Delta * Num;
  2871. NewMemRefs[Refs++] =
  2872. MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize());
  2873. } else {
  2874. NewMI.dropMemRefs();
  2875. return;
  2876. }
  2877. }
  2878. NewMI.setMemRefs(NewMemRefs, NewMemRefs + NumRefs);
  2879. }
  2880. /// Clone the instruction for the new pipelined loop and update the
  2881. /// memory operands, if needed.
  2882. MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
  2883. unsigned CurStageNum,
  2884. unsigned InstStageNum) {
  2885. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  2886. // Check for tied operands in inline asm instructions. This should be handled
  2887. // elsewhere, but I'm not sure of the best solution.
  2888. if (OldMI->isInlineAsm())
  2889. for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
  2890. const auto &MO = OldMI->getOperand(i);
  2891. if (MO.isReg() && MO.isUse())
  2892. break;
  2893. unsigned UseIdx;
  2894. if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
  2895. NewMI->tieOperands(i, UseIdx);
  2896. }
  2897. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  2898. return NewMI;
  2899. }
  2900. /// Clone the instruction for the new pipelined loop. If needed, this
  2901. /// function updates the instruction using the values saved in the
  2902. /// InstrChanges structure.
  2903. MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
  2904. unsigned CurStageNum,
  2905. unsigned InstStageNum,
  2906. SMSchedule &Schedule) {
  2907. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  2908. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  2909. InstrChanges.find(getSUnit(OldMI));
  2910. if (It != InstrChanges.end()) {
  2911. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  2912. unsigned BasePos, OffsetPos;
  2913. if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
  2914. return nullptr;
  2915. int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
  2916. MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
  2917. if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
  2918. NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
  2919. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  2920. }
  2921. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  2922. return NewMI;
  2923. }
  2924. /// Update the machine instruction with new virtual registers. This
  2925. /// function may change the defintions and/or uses.
  2926. void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
  2927. unsigned CurStageNum,
  2928. unsigned InstrStageNum,
  2929. SMSchedule &Schedule,
  2930. ValueMapTy *VRMap) {
  2931. for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
  2932. MachineOperand &MO = NewMI->getOperand(i);
  2933. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  2934. continue;
  2935. unsigned reg = MO.getReg();
  2936. if (MO.isDef()) {
  2937. // Create a new virtual register for the definition.
  2938. const TargetRegisterClass *RC = MRI.getRegClass(reg);
  2939. unsigned NewReg = MRI.createVirtualRegister(RC);
  2940. MO.setReg(NewReg);
  2941. VRMap[CurStageNum][reg] = NewReg;
  2942. if (LastDef)
  2943. replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
  2944. } else if (MO.isUse()) {
  2945. MachineInstr *Def = MRI.getVRegDef(reg);
  2946. // Compute the stage that contains the last definition for instruction.
  2947. int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
  2948. unsigned StageNum = CurStageNum;
  2949. if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
  2950. // Compute the difference in stages between the defintion and the use.
  2951. unsigned StageDiff = (InstrStageNum - DefStageNum);
  2952. // Make an adjustment to get the last definition.
  2953. StageNum -= StageDiff;
  2954. }
  2955. if (VRMap[StageNum].count(reg))
  2956. MO.setReg(VRMap[StageNum][reg]);
  2957. }
  2958. }
  2959. }
  2960. /// Return the instruction in the loop that defines the register.
  2961. /// If the definition is a Phi, then follow the Phi operand to
  2962. /// the instruction in the loop.
  2963. MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
  2964. SmallPtrSet<MachineInstr *, 8> Visited;
  2965. MachineInstr *Def = MRI.getVRegDef(Reg);
  2966. while (Def->isPHI()) {
  2967. if (!Visited.insert(Def).second)
  2968. break;
  2969. for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
  2970. if (Def->getOperand(i + 1).getMBB() == BB) {
  2971. Def = MRI.getVRegDef(Def->getOperand(i).getReg());
  2972. break;
  2973. }
  2974. }
  2975. return Def;
  2976. }
  2977. /// Return the new name for the value from the previous stage.
  2978. unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
  2979. unsigned LoopVal, unsigned LoopStage,
  2980. ValueMapTy *VRMap,
  2981. MachineBasicBlock *BB) {
  2982. unsigned PrevVal = 0;
  2983. if (StageNum > PhiStage) {
  2984. MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
  2985. if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
  2986. // The name is defined in the previous stage.
  2987. PrevVal = VRMap[StageNum - 1][LoopVal];
  2988. else if (VRMap[StageNum].count(LoopVal))
  2989. // The previous name is defined in the current stage when the instruction
  2990. // order is swapped.
  2991. PrevVal = VRMap[StageNum][LoopVal];
  2992. else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
  2993. // The loop value hasn't yet been scheduled.
  2994. PrevVal = LoopVal;
  2995. else if (StageNum == PhiStage + 1)
  2996. // The loop value is another phi, which has not been scheduled.
  2997. PrevVal = getInitPhiReg(*LoopInst, BB);
  2998. else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
  2999. // The loop value is another phi, which has been scheduled.
  3000. PrevVal =
  3001. getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
  3002. LoopStage, VRMap, BB);
  3003. }
  3004. return PrevVal;
  3005. }
  3006. /// Rewrite the Phi values in the specified block to use the mappings
  3007. /// from the initial operand. Once the Phi is scheduled, we switch
  3008. /// to using the loop value instead of the Phi value, so those names
  3009. /// do not need to be rewritten.
  3010. void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
  3011. unsigned StageNum,
  3012. SMSchedule &Schedule,
  3013. ValueMapTy *VRMap,
  3014. InstrMapTy &InstrMap) {
  3015. for (auto &PHI : BB->phis()) {
  3016. unsigned InitVal = 0;
  3017. unsigned LoopVal = 0;
  3018. getPhiRegs(PHI, BB, InitVal, LoopVal);
  3019. unsigned PhiDef = PHI.getOperand(0).getReg();
  3020. unsigned PhiStage =
  3021. (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
  3022. unsigned LoopStage =
  3023. (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
  3024. unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
  3025. if (NumPhis > StageNum)
  3026. NumPhis = StageNum;
  3027. for (unsigned np = 0; np <= NumPhis; ++np) {
  3028. unsigned NewVal =
  3029. getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
  3030. if (!NewVal)
  3031. NewVal = InitVal;
  3032. rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
  3033. PhiDef, NewVal);
  3034. }
  3035. }
  3036. }
  3037. /// Rewrite a previously scheduled instruction to use the register value
  3038. /// from the new instruction. Make sure the instruction occurs in the
  3039. /// basic block, and we don't change the uses in the new instruction.
  3040. void SwingSchedulerDAG::rewriteScheduledInstr(
  3041. MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
  3042. unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
  3043. unsigned NewReg, unsigned PrevReg) {
  3044. bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
  3045. int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
  3046. // Rewrite uses that have been scheduled already to use the new
  3047. // Phi register.
  3048. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
  3049. EI = MRI.use_end();
  3050. UI != EI;) {
  3051. MachineOperand &UseOp = *UI;
  3052. MachineInstr *UseMI = UseOp.getParent();
  3053. ++UI;
  3054. if (UseMI->getParent() != BB)
  3055. continue;
  3056. if (UseMI->isPHI()) {
  3057. if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
  3058. continue;
  3059. if (getLoopPhiReg(*UseMI, BB) != OldReg)
  3060. continue;
  3061. }
  3062. InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
  3063. assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
  3064. SUnit *OrigMISU = getSUnit(OrigInstr->second);
  3065. int StageSched = Schedule.stageScheduled(OrigMISU);
  3066. int CycleSched = Schedule.cycleScheduled(OrigMISU);
  3067. unsigned ReplaceReg = 0;
  3068. // This is the stage for the scheduled instruction.
  3069. if (StagePhi == StageSched && Phi->isPHI()) {
  3070. int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
  3071. if (PrevReg && InProlog)
  3072. ReplaceReg = PrevReg;
  3073. else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
  3074. (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
  3075. ReplaceReg = PrevReg;
  3076. else
  3077. ReplaceReg = NewReg;
  3078. }
  3079. // The scheduled instruction occurs before the scheduled Phi, and the
  3080. // Phi is not loop carried.
  3081. if (!InProlog && StagePhi + 1 == StageSched &&
  3082. !Schedule.isLoopCarried(this, *Phi))
  3083. ReplaceReg = NewReg;
  3084. if (StagePhi > StageSched && Phi->isPHI())
  3085. ReplaceReg = NewReg;
  3086. if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
  3087. ReplaceReg = NewReg;
  3088. if (ReplaceReg) {
  3089. MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
  3090. UseOp.setReg(ReplaceReg);
  3091. }
  3092. }
  3093. }
  3094. /// Check if we can change the instruction to use an offset value from the
  3095. /// previous iteration. If so, return true and set the base and offset values
  3096. /// so that we can rewrite the load, if necessary.
  3097. /// v1 = Phi(v0, v3)
  3098. /// v2 = load v1, 0
  3099. /// v3 = post_store v1, 4, x
  3100. /// This function enables the load to be rewritten as v2 = load v3, 4.
  3101. bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
  3102. unsigned &BasePos,
  3103. unsigned &OffsetPos,
  3104. unsigned &NewBase,
  3105. int64_t &Offset) {
  3106. // Get the load instruction.
  3107. if (TII->isPostIncrement(*MI))
  3108. return false;
  3109. unsigned BasePosLd, OffsetPosLd;
  3110. if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
  3111. return false;
  3112. unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
  3113. // Look for the Phi instruction.
  3114. MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
  3115. MachineInstr *Phi = MRI.getVRegDef(BaseReg);
  3116. if (!Phi || !Phi->isPHI())
  3117. return false;
  3118. // Get the register defined in the loop block.
  3119. unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
  3120. if (!PrevReg)
  3121. return false;
  3122. // Check for the post-increment load/store instruction.
  3123. MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
  3124. if (!PrevDef || PrevDef == MI)
  3125. return false;
  3126. if (!TII->isPostIncrement(*PrevDef))
  3127. return false;
  3128. unsigned BasePos1 = 0, OffsetPos1 = 0;
  3129. if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
  3130. return false;
  3131. // Make sure that the instructions do not access the same memory location in
  3132. // the next iteration.
  3133. int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
  3134. int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
  3135. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  3136. NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
  3137. bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
  3138. MF.DeleteMachineInstr(NewMI);
  3139. if (!Disjoint)
  3140. return false;
  3141. // Set the return value once we determine that we return true.
  3142. BasePos = BasePosLd;
  3143. OffsetPos = OffsetPosLd;
  3144. NewBase = PrevReg;
  3145. Offset = StoreOffset;
  3146. return true;
  3147. }
  3148. /// Apply changes to the instruction if needed. The changes are need
  3149. /// to improve the scheduling and depend up on the final schedule.
  3150. void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
  3151. SMSchedule &Schedule) {
  3152. SUnit *SU = getSUnit(MI);
  3153. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  3154. InstrChanges.find(SU);
  3155. if (It != InstrChanges.end()) {
  3156. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  3157. unsigned BasePos, OffsetPos;
  3158. if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  3159. return;
  3160. unsigned BaseReg = MI->getOperand(BasePos).getReg();
  3161. MachineInstr *LoopDef = findDefInLoop(BaseReg);
  3162. int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
  3163. int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
  3164. int BaseStageNum = Schedule.stageScheduled(SU);
  3165. int BaseCycleNum = Schedule.cycleScheduled(SU);
  3166. if (BaseStageNum < DefStageNum) {
  3167. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  3168. int OffsetDiff = DefStageNum - BaseStageNum;
  3169. if (DefCycleNum < BaseCycleNum) {
  3170. NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
  3171. if (OffsetDiff > 0)
  3172. --OffsetDiff;
  3173. }
  3174. int64_t NewOffset =
  3175. MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
  3176. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  3177. SU->setInstr(NewMI);
  3178. MISUnitMap[NewMI] = SU;
  3179. NewMIs.insert(NewMI);
  3180. }
  3181. }
  3182. }
  3183. /// Return true for an order or output dependence that is loop carried
  3184. /// potentially. A dependence is loop carried if the destination defines a valu
  3185. /// that may be used or defined by the source in a subsequent iteration.
  3186. bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
  3187. bool isSucc) {
  3188. if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
  3189. Dep.isArtificial())
  3190. return false;
  3191. if (!SwpPruneLoopCarried)
  3192. return true;
  3193. if (Dep.getKind() == SDep::Output)
  3194. return true;
  3195. MachineInstr *SI = Source->getInstr();
  3196. MachineInstr *DI = Dep.getSUnit()->getInstr();
  3197. if (!isSucc)
  3198. std::swap(SI, DI);
  3199. assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
  3200. // Assume ordered loads and stores may have a loop carried dependence.
  3201. if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
  3202. SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
  3203. return true;
  3204. // Only chain dependences between a load and store can be loop carried.
  3205. if (!DI->mayStore() || !SI->mayLoad())
  3206. return false;
  3207. unsigned DeltaS, DeltaD;
  3208. if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
  3209. return true;
  3210. unsigned BaseRegS, BaseRegD;
  3211. int64_t OffsetS, OffsetD;
  3212. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  3213. if (!TII->getMemOpBaseRegImmOfs(*SI, BaseRegS, OffsetS, TRI) ||
  3214. !TII->getMemOpBaseRegImmOfs(*DI, BaseRegD, OffsetD, TRI))
  3215. return true;
  3216. if (BaseRegS != BaseRegD)
  3217. return true;
  3218. // Check that the base register is incremented by a constant value for each
  3219. // iteration.
  3220. MachineInstr *Def = MRI.getVRegDef(BaseRegS);
  3221. if (!Def || !Def->isPHI())
  3222. return true;
  3223. unsigned InitVal = 0;
  3224. unsigned LoopVal = 0;
  3225. getPhiRegs(*Def, BB, InitVal, LoopVal);
  3226. MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
  3227. int D = 0;
  3228. if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
  3229. return true;
  3230. uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
  3231. uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
  3232. // This is the main test, which checks the offset values and the loop
  3233. // increment value to determine if the accesses may be loop carried.
  3234. if (OffsetS >= OffsetD)
  3235. return OffsetS + AccessSizeS > DeltaS;
  3236. else
  3237. return OffsetD + AccessSizeD > DeltaD;
  3238. return true;
  3239. }
  3240. void SwingSchedulerDAG::postprocessDAG() {
  3241. for (auto &M : Mutations)
  3242. M->apply(this);
  3243. }
  3244. /// Try to schedule the node at the specified StartCycle and continue
  3245. /// until the node is schedule or the EndCycle is reached. This function
  3246. /// returns true if the node is scheduled. This routine may search either
  3247. /// forward or backward for a place to insert the instruction based upon
  3248. /// the relative values of StartCycle and EndCycle.
  3249. bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
  3250. bool forward = true;
  3251. if (StartCycle > EndCycle)
  3252. forward = false;
  3253. // The terminating condition depends on the direction.
  3254. int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
  3255. for (int curCycle = StartCycle; curCycle != termCycle;
  3256. forward ? ++curCycle : --curCycle) {
  3257. // Add the already scheduled instructions at the specified cycle to the DFA.
  3258. Resources->clearResources();
  3259. for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
  3260. checkCycle <= LastCycle; checkCycle += II) {
  3261. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
  3262. for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
  3263. E = cycleInstrs.end();
  3264. I != E; ++I) {
  3265. if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
  3266. continue;
  3267. assert(Resources->canReserveResources(*(*I)->getInstr()) &&
  3268. "These instructions have already been scheduled.");
  3269. Resources->reserveResources(*(*I)->getInstr());
  3270. }
  3271. }
  3272. if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
  3273. Resources->canReserveResources(*SU->getInstr())) {
  3274. DEBUG({
  3275. dbgs() << "\tinsert at cycle " << curCycle << " ";
  3276. SU->getInstr()->dump();
  3277. });
  3278. ScheduledInstrs[curCycle].push_back(SU);
  3279. InstrToCycle.insert(std::make_pair(SU, curCycle));
  3280. if (curCycle > LastCycle)
  3281. LastCycle = curCycle;
  3282. if (curCycle < FirstCycle)
  3283. FirstCycle = curCycle;
  3284. return true;
  3285. }
  3286. DEBUG({
  3287. dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
  3288. SU->getInstr()->dump();
  3289. });
  3290. }
  3291. return false;
  3292. }
  3293. // Return the cycle of the earliest scheduled instruction in the chain.
  3294. int SMSchedule::earliestCycleInChain(const SDep &Dep) {
  3295. SmallPtrSet<SUnit *, 8> Visited;
  3296. SmallVector<SDep, 8> Worklist;
  3297. Worklist.push_back(Dep);
  3298. int EarlyCycle = INT_MAX;
  3299. while (!Worklist.empty()) {
  3300. const SDep &Cur = Worklist.pop_back_val();
  3301. SUnit *PrevSU = Cur.getSUnit();
  3302. if (Visited.count(PrevSU))
  3303. continue;
  3304. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
  3305. if (it == InstrToCycle.end())
  3306. continue;
  3307. EarlyCycle = std::min(EarlyCycle, it->second);
  3308. for (const auto &PI : PrevSU->Preds)
  3309. if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  3310. Worklist.push_back(PI);
  3311. Visited.insert(PrevSU);
  3312. }
  3313. return EarlyCycle;
  3314. }
  3315. // Return the cycle of the latest scheduled instruction in the chain.
  3316. int SMSchedule::latestCycleInChain(const SDep &Dep) {
  3317. SmallPtrSet<SUnit *, 8> Visited;
  3318. SmallVector<SDep, 8> Worklist;
  3319. Worklist.push_back(Dep);
  3320. int LateCycle = INT_MIN;
  3321. while (!Worklist.empty()) {
  3322. const SDep &Cur = Worklist.pop_back_val();
  3323. SUnit *SuccSU = Cur.getSUnit();
  3324. if (Visited.count(SuccSU))
  3325. continue;
  3326. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
  3327. if (it == InstrToCycle.end())
  3328. continue;
  3329. LateCycle = std::max(LateCycle, it->second);
  3330. for (const auto &SI : SuccSU->Succs)
  3331. if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  3332. Worklist.push_back(SI);
  3333. Visited.insert(SuccSU);
  3334. }
  3335. return LateCycle;
  3336. }
  3337. /// If an instruction has a use that spans multiple iterations, then
  3338. /// return true. These instructions are characterized by having a back-ege
  3339. /// to a Phi, which contains a reference to another Phi.
  3340. static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
  3341. for (auto &P : SU->Preds)
  3342. if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
  3343. for (auto &S : P.getSUnit()->Succs)
  3344. if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
  3345. return P.getSUnit();
  3346. return nullptr;
  3347. }
  3348. /// Compute the scheduling start slot for the instruction. The start slot
  3349. /// depends on any predecessor or successor nodes scheduled already.
  3350. void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
  3351. int *MinEnd, int *MaxStart, int II,
  3352. SwingSchedulerDAG *DAG) {
  3353. // Iterate over each instruction that has been scheduled already. The start
  3354. // slot computuation depends on whether the previously scheduled instruction
  3355. // is a predecessor or successor of the specified instruction.
  3356. for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
  3357. // Iterate over each instruction in the current cycle.
  3358. for (SUnit *I : getInstructions(cycle)) {
  3359. // Because we're processing a DAG for the dependences, we recognize
  3360. // the back-edge in recurrences by anti dependences.
  3361. for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
  3362. const SDep &Dep = SU->Preds[i];
  3363. if (Dep.getSUnit() == I) {
  3364. if (!DAG->isBackedge(SU, Dep)) {
  3365. int EarlyStart = cycle + Dep.getLatency() -
  3366. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  3367. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  3368. if (DAG->isLoopCarriedDep(SU, Dep, false)) {
  3369. int End = earliestCycleInChain(Dep) + (II - 1);
  3370. *MinEnd = std::min(*MinEnd, End);
  3371. }
  3372. } else {
  3373. int LateStart = cycle - Dep.getLatency() +
  3374. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  3375. *MinLateStart = std::min(*MinLateStart, LateStart);
  3376. }
  3377. }
  3378. // For instruction that requires multiple iterations, make sure that
  3379. // the dependent instruction is not scheduled past the definition.
  3380. SUnit *BE = multipleIterations(I, DAG);
  3381. if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
  3382. !SU->isPred(I))
  3383. *MinLateStart = std::min(*MinLateStart, cycle);
  3384. }
  3385. for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
  3386. if (SU->Succs[i].getSUnit() == I) {
  3387. const SDep &Dep = SU->Succs[i];
  3388. if (!DAG->isBackedge(SU, Dep)) {
  3389. int LateStart = cycle - Dep.getLatency() +
  3390. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  3391. *MinLateStart = std::min(*MinLateStart, LateStart);
  3392. if (DAG->isLoopCarriedDep(SU, Dep)) {
  3393. int Start = latestCycleInChain(Dep) + 1 - II;
  3394. *MaxStart = std::max(*MaxStart, Start);
  3395. }
  3396. } else {
  3397. int EarlyStart = cycle + Dep.getLatency() -
  3398. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  3399. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  3400. }
  3401. }
  3402. }
  3403. }
  3404. }
  3405. }
  3406. /// Order the instructions within a cycle so that the definitions occur
  3407. /// before the uses. Returns true if the instruction is added to the start
  3408. /// of the list, or false if added to the end.
  3409. void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
  3410. std::deque<SUnit *> &Insts) {
  3411. MachineInstr *MI = SU->getInstr();
  3412. bool OrderBeforeUse = false;
  3413. bool OrderAfterDef = false;
  3414. bool OrderBeforeDef = false;
  3415. unsigned MoveDef = 0;
  3416. unsigned MoveUse = 0;
  3417. int StageInst1 = stageScheduled(SU);
  3418. unsigned Pos = 0;
  3419. for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
  3420. ++I, ++Pos) {
  3421. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3422. MachineOperand &MO = MI->getOperand(i);
  3423. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  3424. continue;
  3425. unsigned Reg = MO.getReg();
  3426. unsigned BasePos, OffsetPos;
  3427. if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  3428. if (MI->getOperand(BasePos).getReg() == Reg)
  3429. if (unsigned NewReg = SSD->getInstrBaseReg(SU))
  3430. Reg = NewReg;
  3431. bool Reads, Writes;
  3432. std::tie(Reads, Writes) =
  3433. (*I)->getInstr()->readsWritesVirtualRegister(Reg);
  3434. if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
  3435. OrderBeforeUse = true;
  3436. if (MoveUse == 0)
  3437. MoveUse = Pos;
  3438. } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
  3439. // Add the instruction after the scheduled instruction.
  3440. OrderAfterDef = true;
  3441. MoveDef = Pos;
  3442. } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
  3443. if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
  3444. OrderBeforeUse = true;
  3445. if (MoveUse == 0)
  3446. MoveUse = Pos;
  3447. } else {
  3448. OrderAfterDef = true;
  3449. MoveDef = Pos;
  3450. }
  3451. } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
  3452. OrderBeforeUse = true;
  3453. if (MoveUse == 0)
  3454. MoveUse = Pos;
  3455. if (MoveUse != 0) {
  3456. OrderAfterDef = true;
  3457. MoveDef = Pos - 1;
  3458. }
  3459. } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
  3460. // Add the instruction before the scheduled instruction.
  3461. OrderBeforeUse = true;
  3462. if (MoveUse == 0)
  3463. MoveUse = Pos;
  3464. } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
  3465. isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
  3466. if (MoveUse == 0) {
  3467. OrderBeforeDef = true;
  3468. MoveUse = Pos;
  3469. }
  3470. }
  3471. }
  3472. // Check for order dependences between instructions. Make sure the source
  3473. // is ordered before the destination.
  3474. for (auto &S : SU->Succs) {
  3475. if (S.getSUnit() != *I)
  3476. continue;
  3477. if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  3478. OrderBeforeUse = true;
  3479. if (Pos < MoveUse)
  3480. MoveUse = Pos;
  3481. }
  3482. }
  3483. for (auto &P : SU->Preds) {
  3484. if (P.getSUnit() != *I)
  3485. continue;
  3486. if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  3487. OrderAfterDef = true;
  3488. MoveDef = Pos;
  3489. }
  3490. }
  3491. }
  3492. // A circular dependence.
  3493. if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
  3494. OrderBeforeUse = false;
  3495. // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
  3496. // to a loop-carried dependence.
  3497. if (OrderBeforeDef)
  3498. OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
  3499. // The uncommon case when the instruction order needs to be updated because
  3500. // there is both a use and def.
  3501. if (OrderBeforeUse && OrderAfterDef) {
  3502. SUnit *UseSU = Insts.at(MoveUse);
  3503. SUnit *DefSU = Insts.at(MoveDef);
  3504. if (MoveUse > MoveDef) {
  3505. Insts.erase(Insts.begin() + MoveUse);
  3506. Insts.erase(Insts.begin() + MoveDef);
  3507. } else {
  3508. Insts.erase(Insts.begin() + MoveDef);
  3509. Insts.erase(Insts.begin() + MoveUse);
  3510. }
  3511. orderDependence(SSD, UseSU, Insts);
  3512. orderDependence(SSD, SU, Insts);
  3513. orderDependence(SSD, DefSU, Insts);
  3514. return;
  3515. }
  3516. // Put the new instruction first if there is a use in the list. Otherwise,
  3517. // put it at the end of the list.
  3518. if (OrderBeforeUse)
  3519. Insts.push_front(SU);
  3520. else
  3521. Insts.push_back(SU);
  3522. }
  3523. /// Return true if the scheduled Phi has a loop carried operand.
  3524. bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
  3525. if (!Phi.isPHI())
  3526. return false;
  3527. assert(Phi.isPHI() && "Expecing a Phi.");
  3528. SUnit *DefSU = SSD->getSUnit(&Phi);
  3529. unsigned DefCycle = cycleScheduled(DefSU);
  3530. int DefStage = stageScheduled(DefSU);
  3531. unsigned InitVal = 0;
  3532. unsigned LoopVal = 0;
  3533. getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
  3534. SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
  3535. if (!UseSU)
  3536. return true;
  3537. if (UseSU->getInstr()->isPHI())
  3538. return true;
  3539. unsigned LoopCycle = cycleScheduled(UseSU);
  3540. int LoopStage = stageScheduled(UseSU);
  3541. return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
  3542. }
  3543. /// Return true if the instruction is a definition that is loop carried
  3544. /// and defines the use on the next iteration.
  3545. /// v1 = phi(v2, v3)
  3546. /// (Def) v3 = op v1
  3547. /// (MO) = v1
  3548. /// If MO appears before Def, then then v1 and v3 may get assigned to the same
  3549. /// register.
  3550. bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
  3551. MachineInstr *Def, MachineOperand &MO) {
  3552. if (!MO.isReg())
  3553. return false;
  3554. if (Def->isPHI())
  3555. return false;
  3556. MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
  3557. if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
  3558. return false;
  3559. if (!isLoopCarried(SSD, *Phi))
  3560. return false;
  3561. unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
  3562. for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
  3563. MachineOperand &DMO = Def->getOperand(i);
  3564. if (!DMO.isReg() || !DMO.isDef())
  3565. continue;
  3566. if (DMO.getReg() == LoopReg)
  3567. return true;
  3568. }
  3569. return false;
  3570. }
  3571. // Check if the generated schedule is valid. This function checks if
  3572. // an instruction that uses a physical register is scheduled in a
  3573. // different stage than the definition. The pipeliner does not handle
  3574. // physical register values that may cross a basic block boundary.
  3575. bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
  3576. for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
  3577. SUnit &SU = SSD->SUnits[i];
  3578. if (!SU.hasPhysRegDefs)
  3579. continue;
  3580. int StageDef = stageScheduled(&SU);
  3581. assert(StageDef != -1 && "Instruction should have been scheduled.");
  3582. for (auto &SI : SU.Succs)
  3583. if (SI.isAssignedRegDep())
  3584. if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
  3585. if (stageScheduled(SI.getSUnit()) != StageDef)
  3586. return false;
  3587. }
  3588. return true;
  3589. }
  3590. /// A property of the node order in swing-modulo-scheduling is
  3591. /// that for nodes outside circuits the following holds:
  3592. /// none of them is scheduled after both a successor and a
  3593. /// predecessor.
  3594. /// The method below checks whether the property is met.
  3595. /// If not, debug information is printed and statistics information updated.
  3596. /// Note that we do not use an assert statement.
  3597. /// The reason is that although an invalid node oder may prevent
  3598. /// the pipeliner from finding a pipelined schedule for arbitrary II,
  3599. /// it does not lead to the generation of incorrect code.
  3600. void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
  3601. // a sorted vector that maps each SUnit to its index in the NodeOrder
  3602. typedef std::pair<SUnit *, unsigned> UnitIndex;
  3603. std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
  3604. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
  3605. Indices.push_back(std::make_pair(NodeOrder[i], i));
  3606. auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
  3607. return std::get<0>(i1) < std::get<0>(i2);
  3608. };
  3609. // sort, so that we can perform a binary search
  3610. llvm::sort(Indices.begin(), Indices.end(), CompareKey);
  3611. bool Valid = true;
  3612. (void)Valid;
  3613. // for each SUnit in the NodeOrder, check whether
  3614. // it appears after both a successor and a predecessor
  3615. // of the SUnit. If this is the case, and the SUnit
  3616. // is not part of circuit, then the NodeOrder is not
  3617. // valid.
  3618. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
  3619. SUnit *SU = NodeOrder[i];
  3620. unsigned Index = i;
  3621. bool PredBefore = false;
  3622. bool SuccBefore = false;
  3623. SUnit *Succ;
  3624. SUnit *Pred;
  3625. (void)Succ;
  3626. (void)Pred;
  3627. for (SDep &PredEdge : SU->Preds) {
  3628. SUnit *PredSU = PredEdge.getSUnit();
  3629. unsigned PredIndex =
  3630. std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
  3631. std::make_pair(PredSU, 0), CompareKey));
  3632. if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
  3633. PredBefore = true;
  3634. Pred = PredSU;
  3635. break;
  3636. }
  3637. }
  3638. for (SDep &SuccEdge : SU->Succs) {
  3639. SUnit *SuccSU = SuccEdge.getSUnit();
  3640. unsigned SuccIndex =
  3641. std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
  3642. std::make_pair(SuccSU, 0), CompareKey));
  3643. if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
  3644. SuccBefore = true;
  3645. Succ = SuccSU;
  3646. break;
  3647. }
  3648. }
  3649. if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
  3650. // instructions in circuits are allowed to be scheduled
  3651. // after both a successor and predecessor.
  3652. bool InCircuit = std::any_of(
  3653. Circuits.begin(), Circuits.end(),
  3654. [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
  3655. if (InCircuit)
  3656. DEBUG(dbgs() << "In a circuit, predecessor ";);
  3657. else {
  3658. Valid = false;
  3659. NumNodeOrderIssues++;
  3660. DEBUG(dbgs() << "Predecessor ";);
  3661. }
  3662. DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
  3663. << " are scheduled before node " << SU->NodeNum << "\n";);
  3664. }
  3665. }
  3666. DEBUG({
  3667. if (!Valid)
  3668. dbgs() << "Invalid node order found!\n";
  3669. });
  3670. }
  3671. /// Attempt to fix the degenerate cases when the instruction serialization
  3672. /// causes the register lifetimes to overlap. For example,
  3673. /// p' = store_pi(p, b)
  3674. /// = load p, offset
  3675. /// In this case p and p' overlap, which means that two registers are needed.
  3676. /// Instead, this function changes the load to use p' and updates the offset.
  3677. void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
  3678. unsigned OverlapReg = 0;
  3679. unsigned NewBaseReg = 0;
  3680. for (SUnit *SU : Instrs) {
  3681. MachineInstr *MI = SU->getInstr();
  3682. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3683. const MachineOperand &MO = MI->getOperand(i);
  3684. // Look for an instruction that uses p. The instruction occurs in the
  3685. // same cycle but occurs later in the serialized order.
  3686. if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
  3687. // Check that the instruction appears in the InstrChanges structure,
  3688. // which contains instructions that can have the offset updated.
  3689. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  3690. InstrChanges.find(SU);
  3691. if (It != InstrChanges.end()) {
  3692. unsigned BasePos, OffsetPos;
  3693. // Update the base register and adjust the offset.
  3694. if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
  3695. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  3696. NewMI->getOperand(BasePos).setReg(NewBaseReg);
  3697. int64_t NewOffset =
  3698. MI->getOperand(OffsetPos).getImm() - It->second.second;
  3699. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  3700. SU->setInstr(NewMI);
  3701. MISUnitMap[NewMI] = SU;
  3702. NewMIs.insert(NewMI);
  3703. }
  3704. }
  3705. OverlapReg = 0;
  3706. NewBaseReg = 0;
  3707. break;
  3708. }
  3709. // Look for an instruction of the form p' = op(p), which uses and defines
  3710. // two virtual registers that get allocated to the same physical register.
  3711. unsigned TiedUseIdx = 0;
  3712. if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
  3713. // OverlapReg is p in the example above.
  3714. OverlapReg = MI->getOperand(TiedUseIdx).getReg();
  3715. // NewBaseReg is p' in the example above.
  3716. NewBaseReg = MI->getOperand(i).getReg();
  3717. break;
  3718. }
  3719. }
  3720. }
  3721. }
  3722. /// After the schedule has been formed, call this function to combine
  3723. /// the instructions from the different stages/cycles. That is, this
  3724. /// function creates a schedule that represents a single iteration.
  3725. void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
  3726. // Move all instructions to the first stage from later stages.
  3727. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  3728. for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
  3729. ++stage) {
  3730. std::deque<SUnit *> &cycleInstrs =
  3731. ScheduledInstrs[cycle + (stage * InitiationInterval)];
  3732. for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
  3733. E = cycleInstrs.rend();
  3734. I != E; ++I)
  3735. ScheduledInstrs[cycle].push_front(*I);
  3736. }
  3737. }
  3738. // Iterate over the definitions in each instruction, and compute the
  3739. // stage difference for each use. Keep the maximum value.
  3740. for (auto &I : InstrToCycle) {
  3741. int DefStage = stageScheduled(I.first);
  3742. MachineInstr *MI = I.first->getInstr();
  3743. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3744. MachineOperand &Op = MI->getOperand(i);
  3745. if (!Op.isReg() || !Op.isDef())
  3746. continue;
  3747. unsigned Reg = Op.getReg();
  3748. unsigned MaxDiff = 0;
  3749. bool PhiIsSwapped = false;
  3750. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
  3751. EI = MRI.use_end();
  3752. UI != EI; ++UI) {
  3753. MachineOperand &UseOp = *UI;
  3754. MachineInstr *UseMI = UseOp.getParent();
  3755. SUnit *SUnitUse = SSD->getSUnit(UseMI);
  3756. int UseStage = stageScheduled(SUnitUse);
  3757. unsigned Diff = 0;
  3758. if (UseStage != -1 && UseStage >= DefStage)
  3759. Diff = UseStage - DefStage;
  3760. if (MI->isPHI()) {
  3761. if (isLoopCarried(SSD, *MI))
  3762. ++Diff;
  3763. else
  3764. PhiIsSwapped = true;
  3765. }
  3766. MaxDiff = std::max(Diff, MaxDiff);
  3767. }
  3768. RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
  3769. }
  3770. }
  3771. // Erase all the elements in the later stages. Only one iteration should
  3772. // remain in the scheduled list, and it contains all the instructions.
  3773. for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
  3774. ScheduledInstrs.erase(cycle);
  3775. // Change the registers in instruction as specified in the InstrChanges
  3776. // map. We need to use the new registers to create the correct order.
  3777. for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
  3778. SUnit *SU = &SSD->SUnits[i];
  3779. SSD->applyInstrChange(SU->getInstr(), *this);
  3780. }
  3781. // Reorder the instructions in each cycle to fix and improve the
  3782. // generated code.
  3783. for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
  3784. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
  3785. std::deque<SUnit *> newOrderPhi;
  3786. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  3787. SUnit *SU = cycleInstrs[i];
  3788. if (SU->getInstr()->isPHI())
  3789. newOrderPhi.push_back(SU);
  3790. }
  3791. std::deque<SUnit *> newOrderI;
  3792. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  3793. SUnit *SU = cycleInstrs[i];
  3794. if (!SU->getInstr()->isPHI())
  3795. orderDependence(SSD, SU, newOrderI);
  3796. }
  3797. // Replace the old order with the new order.
  3798. cycleInstrs.swap(newOrderPhi);
  3799. cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
  3800. SSD->fixupRegisterOverlaps(cycleInstrs);
  3801. }
  3802. DEBUG(dump(););
  3803. }
  3804. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  3805. /// Print the schedule information to the given output.
  3806. void SMSchedule::print(raw_ostream &os) const {
  3807. // Iterate over each cycle.
  3808. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  3809. // Iterate over each instruction in the cycle.
  3810. const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
  3811. for (SUnit *CI : cycleInstrs->second) {
  3812. os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
  3813. os << "(" << CI->NodeNum << ") ";
  3814. CI->getInstr()->print(os);
  3815. os << "\n";
  3816. }
  3817. }
  3818. }
  3819. /// Utility function used for debugging to print the schedule.
  3820. LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
  3821. #endif