MachinePipeliner.cpp 149 KB

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