MachinePipeliner.cpp 151 KB

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