MachineScheduler.cpp 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609
  1. //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
  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. // MachineScheduler schedules machine instructions after phi elimination. It
  11. // preserves LiveIntervals so it can be invoked before register allocation.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/iterator_range.h"
  18. #include "llvm/ADT/PriorityQueue.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/Analysis/AliasAnalysis.h"
  22. #include "llvm/CodeGen/LiveInterval.h"
  23. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineDominators.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineFunctionPass.h"
  28. #include "llvm/CodeGen/MachineInstr.h"
  29. #include "llvm/CodeGen/MachineLoopInfo.h"
  30. #include "llvm/CodeGen/MachineOperand.h"
  31. #include "llvm/CodeGen/MachinePassRegistry.h"
  32. #include "llvm/CodeGen/RegisterPressure.h"
  33. #include "llvm/CodeGen/MachineRegisterInfo.h"
  34. #include "llvm/CodeGen/MachineScheduler.h"
  35. #include "llvm/CodeGen/MachineValueType.h"
  36. #include "llvm/CodeGen/Passes.h"
  37. #include "llvm/CodeGen/RegisterClassInfo.h"
  38. #include "llvm/CodeGen/ScheduleDAG.h"
  39. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  40. #include "llvm/CodeGen/ScheduleDAGMutation.h"
  41. #include "llvm/CodeGen/ScheduleDFS.h"
  42. #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
  43. #include "llvm/CodeGen/SlotIndexes.h"
  44. #include "llvm/CodeGen/TargetPassConfig.h"
  45. #include "llvm/CodeGen/TargetSchedule.h"
  46. #include "llvm/MC/LaneBitmask.h"
  47. #include "llvm/Pass.h"
  48. #include "llvm/Support/CommandLine.h"
  49. #include "llvm/Support/Compiler.h"
  50. #include "llvm/Support/Debug.h"
  51. #include "llvm/Support/ErrorHandling.h"
  52. #include "llvm/Support/GraphWriter.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include "llvm/Target/TargetInstrInfo.h"
  55. #include "llvm/Target/TargetLowering.h"
  56. #include "llvm/Target/TargetRegisterInfo.h"
  57. #include "llvm/Target/TargetSubtargetInfo.h"
  58. #include <algorithm>
  59. #include <cassert>
  60. #include <cstdint>
  61. #include <iterator>
  62. #include <limits>
  63. #include <memory>
  64. #include <string>
  65. #include <tuple>
  66. #include <utility>
  67. #include <vector>
  68. using namespace llvm;
  69. #define DEBUG_TYPE "misched"
  70. namespace llvm {
  71. cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
  72. cl::desc("Force top-down list scheduling"));
  73. cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
  74. cl::desc("Force bottom-up list scheduling"));
  75. cl::opt<bool>
  76. DumpCriticalPathLength("misched-dcpl", cl::Hidden,
  77. cl::desc("Print critical path length to stdout"));
  78. } // end namespace llvm
  79. #ifndef NDEBUG
  80. static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
  81. cl::desc("Pop up a window to show MISched dags after they are processed"));
  82. /// In some situations a few uninteresting nodes depend on nearly all other
  83. /// nodes in the graph, provide a cutoff to hide them.
  84. static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
  85. cl::desc("Hide nodes with more predecessor/successor than cutoff"));
  86. static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
  87. cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
  88. static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
  89. cl::desc("Only schedule this function"));
  90. static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
  91. cl::desc("Only schedule this MBB#"));
  92. #else
  93. static bool ViewMISchedDAGs = false;
  94. #endif // NDEBUG
  95. /// Avoid quadratic complexity in unusually large basic blocks by limiting the
  96. /// size of the ready lists.
  97. static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
  98. cl::desc("Limit ready list to N instructions"), cl::init(256));
  99. static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
  100. cl::desc("Enable register pressure scheduling."), cl::init(true));
  101. static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
  102. cl::desc("Enable cyclic critical path analysis."), cl::init(true));
  103. static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
  104. cl::desc("Enable memop clustering."),
  105. cl::init(true));
  106. static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
  107. cl::desc("Verify machine instrs before and after machine scheduling"));
  108. // DAG subtrees must have at least this many nodes.
  109. static const unsigned MinSubtreeSize = 8;
  110. // Pin the vtables to this file.
  111. void MachineSchedStrategy::anchor() {}
  112. void ScheduleDAGMutation::anchor() {}
  113. //===----------------------------------------------------------------------===//
  114. // Machine Instruction Scheduling Pass and Registry
  115. //===----------------------------------------------------------------------===//
  116. MachineSchedContext::MachineSchedContext() {
  117. RegClassInfo = new RegisterClassInfo();
  118. }
  119. MachineSchedContext::~MachineSchedContext() {
  120. delete RegClassInfo;
  121. }
  122. namespace {
  123. /// Base class for a machine scheduler class that can run at any point.
  124. class MachineSchedulerBase : public MachineSchedContext,
  125. public MachineFunctionPass {
  126. public:
  127. MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
  128. void print(raw_ostream &O, const Module* = nullptr) const override;
  129. protected:
  130. void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
  131. };
  132. /// MachineScheduler runs after coalescing and before register allocation.
  133. class MachineScheduler : public MachineSchedulerBase {
  134. public:
  135. MachineScheduler();
  136. void getAnalysisUsage(AnalysisUsage &AU) const override;
  137. bool runOnMachineFunction(MachineFunction&) override;
  138. static char ID; // Class identification, replacement for typeinfo
  139. protected:
  140. ScheduleDAGInstrs *createMachineScheduler();
  141. };
  142. /// PostMachineScheduler runs after shortly before code emission.
  143. class PostMachineScheduler : public MachineSchedulerBase {
  144. public:
  145. PostMachineScheduler();
  146. void getAnalysisUsage(AnalysisUsage &AU) const override;
  147. bool runOnMachineFunction(MachineFunction&) override;
  148. static char ID; // Class identification, replacement for typeinfo
  149. protected:
  150. ScheduleDAGInstrs *createPostMachineScheduler();
  151. };
  152. } // end anonymous namespace
  153. char MachineScheduler::ID = 0;
  154. char &llvm::MachineSchedulerID = MachineScheduler::ID;
  155. INITIALIZE_PASS_BEGIN(MachineScheduler, "machine-scheduler",
  156. "Machine Instruction Scheduler", false, false)
  157. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  158. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  159. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  160. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  161. INITIALIZE_PASS_END(MachineScheduler, "machine-scheduler",
  162. "Machine Instruction Scheduler", false, false)
  163. MachineScheduler::MachineScheduler()
  164. : MachineSchedulerBase(ID) {
  165. initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
  166. }
  167. void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
  168. AU.setPreservesCFG();
  169. AU.addRequiredID(MachineDominatorsID);
  170. AU.addRequired<MachineLoopInfo>();
  171. AU.addRequired<AAResultsWrapperPass>();
  172. AU.addRequired<TargetPassConfig>();
  173. AU.addRequired<SlotIndexes>();
  174. AU.addPreserved<SlotIndexes>();
  175. AU.addRequired<LiveIntervals>();
  176. AU.addPreserved<LiveIntervals>();
  177. MachineFunctionPass::getAnalysisUsage(AU);
  178. }
  179. char PostMachineScheduler::ID = 0;
  180. char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
  181. INITIALIZE_PASS(PostMachineScheduler, "postmisched",
  182. "PostRA Machine Instruction Scheduler", false, false)
  183. PostMachineScheduler::PostMachineScheduler()
  184. : MachineSchedulerBase(ID) {
  185. initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
  186. }
  187. void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
  188. AU.setPreservesCFG();
  189. AU.addRequiredID(MachineDominatorsID);
  190. AU.addRequired<MachineLoopInfo>();
  191. AU.addRequired<TargetPassConfig>();
  192. MachineFunctionPass::getAnalysisUsage(AU);
  193. }
  194. MachinePassRegistry MachineSchedRegistry::Registry;
  195. /// A dummy default scheduler factory indicates whether the scheduler
  196. /// is overridden on the command line.
  197. static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
  198. return nullptr;
  199. }
  200. /// MachineSchedOpt allows command line selection of the scheduler.
  201. static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
  202. RegisterPassParser<MachineSchedRegistry>>
  203. MachineSchedOpt("misched",
  204. cl::init(&useDefaultMachineSched), cl::Hidden,
  205. cl::desc("Machine instruction scheduler to use"));
  206. static MachineSchedRegistry
  207. DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
  208. useDefaultMachineSched);
  209. static cl::opt<bool> EnableMachineSched(
  210. "enable-misched",
  211. cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
  212. cl::Hidden);
  213. static cl::opt<bool> EnablePostRAMachineSched(
  214. "enable-post-misched",
  215. cl::desc("Enable the post-ra machine instruction scheduling pass."),
  216. cl::init(true), cl::Hidden);
  217. /// Decrement this iterator until reaching the top or a non-debug instr.
  218. static MachineBasicBlock::const_iterator
  219. priorNonDebug(MachineBasicBlock::const_iterator I,
  220. MachineBasicBlock::const_iterator Beg) {
  221. assert(I != Beg && "reached the top of the region, cannot decrement");
  222. while (--I != Beg) {
  223. if (!I->isDebugValue())
  224. break;
  225. }
  226. return I;
  227. }
  228. /// Non-const version.
  229. static MachineBasicBlock::iterator
  230. priorNonDebug(MachineBasicBlock::iterator I,
  231. MachineBasicBlock::const_iterator Beg) {
  232. return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
  233. .getNonConstIterator();
  234. }
  235. /// If this iterator is a debug value, increment until reaching the End or a
  236. /// non-debug instruction.
  237. static MachineBasicBlock::const_iterator
  238. nextIfDebug(MachineBasicBlock::const_iterator I,
  239. MachineBasicBlock::const_iterator End) {
  240. for(; I != End; ++I) {
  241. if (!I->isDebugValue())
  242. break;
  243. }
  244. return I;
  245. }
  246. /// Non-const version.
  247. static MachineBasicBlock::iterator
  248. nextIfDebug(MachineBasicBlock::iterator I,
  249. MachineBasicBlock::const_iterator End) {
  250. return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
  251. .getNonConstIterator();
  252. }
  253. /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
  254. ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
  255. // Select the scheduler, or set the default.
  256. MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
  257. if (Ctor != useDefaultMachineSched)
  258. return Ctor(this);
  259. // Get the default scheduler set by the target for this function.
  260. ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
  261. if (Scheduler)
  262. return Scheduler;
  263. // Default to GenericScheduler.
  264. return createGenericSchedLive(this);
  265. }
  266. /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
  267. /// the caller. We don't have a command line option to override the postRA
  268. /// scheduler. The Target must configure it.
  269. ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
  270. // Get the postRA scheduler set by the target for this function.
  271. ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
  272. if (Scheduler)
  273. return Scheduler;
  274. // Default to GenericScheduler.
  275. return createGenericSchedPostRA(this);
  276. }
  277. /// Top-level MachineScheduler pass driver.
  278. ///
  279. /// Visit blocks in function order. Divide each block into scheduling regions
  280. /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
  281. /// consistent with the DAG builder, which traverses the interior of the
  282. /// scheduling regions bottom-up.
  283. ///
  284. /// This design avoids exposing scheduling boundaries to the DAG builder,
  285. /// simplifying the DAG builder's support for "special" target instructions.
  286. /// At the same time the design allows target schedulers to operate across
  287. /// scheduling boundaries, for example to bundle the boudary instructions
  288. /// without reordering them. This creates complexity, because the target
  289. /// scheduler must update the RegionBegin and RegionEnd positions cached by
  290. /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
  291. /// design would be to split blocks at scheduling boundaries, but LLVM has a
  292. /// general bias against block splitting purely for implementation simplicity.
  293. bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
  294. if (skipFunction(*mf.getFunction()))
  295. return false;
  296. if (EnableMachineSched.getNumOccurrences()) {
  297. if (!EnableMachineSched)
  298. return false;
  299. } else if (!mf.getSubtarget().enableMachineScheduler())
  300. return false;
  301. DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
  302. // Initialize the context of the pass.
  303. MF = &mf;
  304. MLI = &getAnalysis<MachineLoopInfo>();
  305. MDT = &getAnalysis<MachineDominatorTree>();
  306. PassConfig = &getAnalysis<TargetPassConfig>();
  307. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  308. LIS = &getAnalysis<LiveIntervals>();
  309. if (VerifyScheduling) {
  310. DEBUG(LIS->dump());
  311. MF->verify(this, "Before machine scheduling.");
  312. }
  313. RegClassInfo->runOnMachineFunction(*MF);
  314. // Instantiate the selected scheduler for this target, function, and
  315. // optimization level.
  316. std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
  317. scheduleRegions(*Scheduler, false);
  318. DEBUG(LIS->dump());
  319. if (VerifyScheduling)
  320. MF->verify(this, "After machine scheduling.");
  321. return true;
  322. }
  323. bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
  324. if (skipFunction(*mf.getFunction()))
  325. return false;
  326. if (EnablePostRAMachineSched.getNumOccurrences()) {
  327. if (!EnablePostRAMachineSched)
  328. return false;
  329. } else if (!mf.getSubtarget().enablePostRAScheduler()) {
  330. DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
  331. return false;
  332. }
  333. DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
  334. // Initialize the context of the pass.
  335. MF = &mf;
  336. PassConfig = &getAnalysis<TargetPassConfig>();
  337. if (VerifyScheduling)
  338. MF->verify(this, "Before post machine scheduling.");
  339. // Instantiate the selected scheduler for this target, function, and
  340. // optimization level.
  341. std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
  342. scheduleRegions(*Scheduler, true);
  343. if (VerifyScheduling)
  344. MF->verify(this, "After post machine scheduling.");
  345. return true;
  346. }
  347. /// Return true of the given instruction should not be included in a scheduling
  348. /// region.
  349. ///
  350. /// MachineScheduler does not currently support scheduling across calls. To
  351. /// handle calls, the DAG builder needs to be modified to create register
  352. /// anti/output dependencies on the registers clobbered by the call's regmask
  353. /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
  354. /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
  355. /// the boundary, but there would be no benefit to postRA scheduling across
  356. /// calls this late anyway.
  357. static bool isSchedBoundary(MachineBasicBlock::iterator MI,
  358. MachineBasicBlock *MBB,
  359. MachineFunction *MF,
  360. const TargetInstrInfo *TII) {
  361. return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
  362. }
  363. /// Main driver for both MachineScheduler and PostMachineScheduler.
  364. void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
  365. bool FixKillFlags) {
  366. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  367. // Visit all machine basic blocks.
  368. //
  369. // TODO: Visit blocks in global postorder or postorder within the bottom-up
  370. // loop tree. Then we can optionally compute global RegPressure.
  371. for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
  372. MBB != MBBEnd; ++MBB) {
  373. Scheduler.startBlock(&*MBB);
  374. #ifndef NDEBUG
  375. if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
  376. continue;
  377. if (SchedOnlyBlock.getNumOccurrences()
  378. && (int)SchedOnlyBlock != MBB->getNumber())
  379. continue;
  380. #endif
  381. // Break the block into scheduling regions [I, RegionEnd), and schedule each
  382. // region as soon as it is discovered. RegionEnd points the scheduling
  383. // boundary at the bottom of the region. The DAG does not include RegionEnd,
  384. // but the region does (i.e. the next RegionEnd is above the previous
  385. // RegionBegin). If the current block has no terminator then RegionEnd ==
  386. // MBB->end() for the bottom region.
  387. //
  388. // The Scheduler may insert instructions during either schedule() or
  389. // exitRegion(), even for empty regions. So the local iterators 'I' and
  390. // 'RegionEnd' are invalid across these calls.
  391. //
  392. // MBB::size() uses instr_iterator to count. Here we need a bundle to count
  393. // as a single instruction.
  394. for(MachineBasicBlock::iterator RegionEnd = MBB->end();
  395. RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
  396. // Avoid decrementing RegionEnd for blocks with no terminator.
  397. if (RegionEnd != MBB->end() ||
  398. isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
  399. --RegionEnd;
  400. }
  401. // The next region starts above the previous region. Look backward in the
  402. // instruction stream until we find the nearest boundary.
  403. unsigned NumRegionInstrs = 0;
  404. MachineBasicBlock::iterator I = RegionEnd;
  405. for (; I != MBB->begin(); --I) {
  406. MachineInstr &MI = *std::prev(I);
  407. if (isSchedBoundary(&MI, &*MBB, MF, TII))
  408. break;
  409. if (!MI.isDebugValue())
  410. ++NumRegionInstrs;
  411. }
  412. // Notify the scheduler of the region, even if we may skip scheduling
  413. // it. Perhaps it still needs to be bundled.
  414. Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
  415. // Skip empty scheduling regions (0 or 1 schedulable instructions).
  416. if (I == RegionEnd || I == std::prev(RegionEnd)) {
  417. // Close the current region. Bundle the terminator if needed.
  418. // This invalidates 'RegionEnd' and 'I'.
  419. Scheduler.exitRegion();
  420. continue;
  421. }
  422. DEBUG(dbgs() << "********** MI Scheduling **********\n");
  423. DEBUG(dbgs() << MF->getName()
  424. << ":BB#" << MBB->getNumber() << " " << MBB->getName()
  425. << "\n From: " << *I << " To: ";
  426. if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
  427. else dbgs() << "End";
  428. dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
  429. if (DumpCriticalPathLength) {
  430. errs() << MF->getName();
  431. errs() << ":BB# " << MBB->getNumber();
  432. errs() << " " << MBB->getName() << " \n";
  433. }
  434. // Schedule a region: possibly reorder instructions.
  435. // This invalidates 'RegionEnd' and 'I'.
  436. Scheduler.schedule();
  437. // Close the current region.
  438. Scheduler.exitRegion();
  439. // Scheduling has invalidated the current iterator 'I'. Ask the
  440. // scheduler for the top of it's scheduled region.
  441. RegionEnd = Scheduler.begin();
  442. }
  443. Scheduler.finishBlock();
  444. // FIXME: Ideally, no further passes should rely on kill flags. However,
  445. // thumb2 size reduction is currently an exception, so the PostMIScheduler
  446. // needs to do this.
  447. if (FixKillFlags)
  448. Scheduler.fixupKills(&*MBB);
  449. }
  450. Scheduler.finalizeSchedule();
  451. }
  452. void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
  453. // unimplemented
  454. }
  455. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  456. LLVM_DUMP_METHOD void ReadyQueue::dump() {
  457. dbgs() << "Queue " << Name << ": ";
  458. for (unsigned i = 0, e = Queue.size(); i < e; ++i)
  459. dbgs() << Queue[i]->NodeNum << " ";
  460. dbgs() << "\n";
  461. }
  462. #endif
  463. //===----------------------------------------------------------------------===//
  464. // ScheduleDAGMI - Basic machine instruction scheduling. This is
  465. // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
  466. // virtual registers.
  467. // ===----------------------------------------------------------------------===/
  468. // Provide a vtable anchor.
  469. ScheduleDAGMI::~ScheduleDAGMI() = default;
  470. bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
  471. return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
  472. }
  473. bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
  474. if (SuccSU != &ExitSU) {
  475. // Do not use WillCreateCycle, it assumes SD scheduling.
  476. // If Pred is reachable from Succ, then the edge creates a cycle.
  477. if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
  478. return false;
  479. Topo.AddPred(SuccSU, PredDep.getSUnit());
  480. }
  481. SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
  482. // Return true regardless of whether a new edge needed to be inserted.
  483. return true;
  484. }
  485. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
  486. /// NumPredsLeft reaches zero, release the successor node.
  487. ///
  488. /// FIXME: Adjust SuccSU height based on MinLatency.
  489. void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
  490. SUnit *SuccSU = SuccEdge->getSUnit();
  491. if (SuccEdge->isWeak()) {
  492. --SuccSU->WeakPredsLeft;
  493. if (SuccEdge->isCluster())
  494. NextClusterSucc = SuccSU;
  495. return;
  496. }
  497. #ifndef NDEBUG
  498. if (SuccSU->NumPredsLeft == 0) {
  499. dbgs() << "*** Scheduling failed! ***\n";
  500. SuccSU->dump(this);
  501. dbgs() << " has been released too many times!\n";
  502. llvm_unreachable(nullptr);
  503. }
  504. #endif
  505. // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
  506. // CurrCycle may have advanced since then.
  507. if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
  508. SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
  509. --SuccSU->NumPredsLeft;
  510. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  511. SchedImpl->releaseTopNode(SuccSU);
  512. }
  513. /// releaseSuccessors - Call releaseSucc on each of SU's successors.
  514. void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
  515. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  516. I != E; ++I) {
  517. releaseSucc(SU, &*I);
  518. }
  519. }
  520. /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
  521. /// NumSuccsLeft reaches zero, release the predecessor node.
  522. ///
  523. /// FIXME: Adjust PredSU height based on MinLatency.
  524. void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
  525. SUnit *PredSU = PredEdge->getSUnit();
  526. if (PredEdge->isWeak()) {
  527. --PredSU->WeakSuccsLeft;
  528. if (PredEdge->isCluster())
  529. NextClusterPred = PredSU;
  530. return;
  531. }
  532. #ifndef NDEBUG
  533. if (PredSU->NumSuccsLeft == 0) {
  534. dbgs() << "*** Scheduling failed! ***\n";
  535. PredSU->dump(this);
  536. dbgs() << " has been released too many times!\n";
  537. llvm_unreachable(nullptr);
  538. }
  539. #endif
  540. // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
  541. // CurrCycle may have advanced since then.
  542. if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
  543. PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
  544. --PredSU->NumSuccsLeft;
  545. if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
  546. SchedImpl->releaseBottomNode(PredSU);
  547. }
  548. /// releasePredecessors - Call releasePred on each of SU's predecessors.
  549. void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
  550. for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
  551. I != E; ++I) {
  552. releasePred(SU, &*I);
  553. }
  554. }
  555. /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
  556. /// crossing a scheduling boundary. [begin, end) includes all instructions in
  557. /// the region, including the boundary itself and single-instruction regions
  558. /// that don't get scheduled.
  559. void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
  560. MachineBasicBlock::iterator begin,
  561. MachineBasicBlock::iterator end,
  562. unsigned regioninstrs)
  563. {
  564. ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
  565. SchedImpl->initPolicy(begin, end, regioninstrs);
  566. }
  567. /// This is normally called from the main scheduler loop but may also be invoked
  568. /// by the scheduling strategy to perform additional code motion.
  569. void ScheduleDAGMI::moveInstruction(
  570. MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
  571. // Advance RegionBegin if the first instruction moves down.
  572. if (&*RegionBegin == MI)
  573. ++RegionBegin;
  574. // Update the instruction stream.
  575. BB->splice(InsertPos, BB, MI);
  576. // Update LiveIntervals
  577. if (LIS)
  578. LIS->handleMove(*MI, /*UpdateFlags=*/true);
  579. // Recede RegionBegin if an instruction moves above the first.
  580. if (RegionBegin == InsertPos)
  581. RegionBegin = MI;
  582. }
  583. bool ScheduleDAGMI::checkSchedLimit() {
  584. #ifndef NDEBUG
  585. if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
  586. CurrentTop = CurrentBottom;
  587. return false;
  588. }
  589. ++NumInstrsScheduled;
  590. #endif
  591. return true;
  592. }
  593. /// Per-region scheduling driver, called back from
  594. /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
  595. /// does not consider liveness or register pressure. It is useful for PostRA
  596. /// scheduling and potentially other custom schedulers.
  597. void ScheduleDAGMI::schedule() {
  598. DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
  599. DEBUG(SchedImpl->dumpPolicy());
  600. // Build the DAG.
  601. buildSchedGraph(AA);
  602. Topo.InitDAGTopologicalSorting();
  603. postprocessDAG();
  604. SmallVector<SUnit*, 8> TopRoots, BotRoots;
  605. findRootsAndBiasEdges(TopRoots, BotRoots);
  606. // Initialize the strategy before modifying the DAG.
  607. // This may initialize a DFSResult to be used for queue priority.
  608. SchedImpl->initialize(this);
  609. DEBUG(
  610. if (EntrySU.getInstr() != nullptr)
  611. EntrySU.dumpAll(this);
  612. for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  613. SUnits[su].dumpAll(this);
  614. if (ExitSU.getInstr() != nullptr)
  615. ExitSU.dumpAll(this);
  616. );
  617. if (ViewMISchedDAGs) viewGraph();
  618. // Initialize ready queues now that the DAG and priority data are finalized.
  619. initQueues(TopRoots, BotRoots);
  620. bool IsTopNode = false;
  621. while (true) {
  622. DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
  623. SUnit *SU = SchedImpl->pickNode(IsTopNode);
  624. if (!SU) break;
  625. assert(!SU->isScheduled && "Node already scheduled");
  626. if (!checkSchedLimit())
  627. break;
  628. MachineInstr *MI = SU->getInstr();
  629. if (IsTopNode) {
  630. assert(SU->isTopReady() && "node still has unscheduled dependencies");
  631. if (&*CurrentTop == MI)
  632. CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
  633. else
  634. moveInstruction(MI, CurrentTop);
  635. } else {
  636. assert(SU->isBottomReady() && "node still has unscheduled dependencies");
  637. MachineBasicBlock::iterator priorII =
  638. priorNonDebug(CurrentBottom, CurrentTop);
  639. if (&*priorII == MI)
  640. CurrentBottom = priorII;
  641. else {
  642. if (&*CurrentTop == MI)
  643. CurrentTop = nextIfDebug(++CurrentTop, priorII);
  644. moveInstruction(MI, CurrentBottom);
  645. CurrentBottom = MI;
  646. }
  647. }
  648. // Notify the scheduling strategy before updating the DAG.
  649. // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
  650. // runs, it can then use the accurate ReadyCycle time to determine whether
  651. // newly released nodes can move to the readyQ.
  652. SchedImpl->schedNode(SU, IsTopNode);
  653. updateQueues(SU, IsTopNode);
  654. }
  655. assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
  656. placeDebugValues();
  657. DEBUG({
  658. unsigned BBNum = begin()->getParent()->getNumber();
  659. dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
  660. dumpSchedule();
  661. dbgs() << '\n';
  662. });
  663. }
  664. /// Apply each ScheduleDAGMutation step in order.
  665. void ScheduleDAGMI::postprocessDAG() {
  666. for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
  667. Mutations[i]->apply(this);
  668. }
  669. }
  670. void ScheduleDAGMI::
  671. findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
  672. SmallVectorImpl<SUnit*> &BotRoots) {
  673. for (std::vector<SUnit>::iterator
  674. I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
  675. SUnit *SU = &(*I);
  676. assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
  677. // Order predecessors so DFSResult follows the critical path.
  678. SU->biasCriticalPath();
  679. // A SUnit is ready to top schedule if it has no predecessors.
  680. if (!I->NumPredsLeft)
  681. TopRoots.push_back(SU);
  682. // A SUnit is ready to bottom schedule if it has no successors.
  683. if (!I->NumSuccsLeft)
  684. BotRoots.push_back(SU);
  685. }
  686. ExitSU.biasCriticalPath();
  687. }
  688. /// Identify DAG roots and setup scheduler queues.
  689. void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
  690. ArrayRef<SUnit*> BotRoots) {
  691. NextClusterSucc = nullptr;
  692. NextClusterPred = nullptr;
  693. // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
  694. //
  695. // Nodes with unreleased weak edges can still be roots.
  696. // Release top roots in forward order.
  697. for (SmallVectorImpl<SUnit*>::const_iterator
  698. I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
  699. SchedImpl->releaseTopNode(*I);
  700. }
  701. // Release bottom roots in reverse order so the higher priority nodes appear
  702. // first. This is more natural and slightly more efficient.
  703. for (SmallVectorImpl<SUnit*>::const_reverse_iterator
  704. I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
  705. SchedImpl->releaseBottomNode(*I);
  706. }
  707. releaseSuccessors(&EntrySU);
  708. releasePredecessors(&ExitSU);
  709. SchedImpl->registerRoots();
  710. // Advance past initial DebugValues.
  711. CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
  712. CurrentBottom = RegionEnd;
  713. }
  714. /// Update scheduler queues after scheduling an instruction.
  715. void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
  716. // Release dependent instructions for scheduling.
  717. if (IsTopNode)
  718. releaseSuccessors(SU);
  719. else
  720. releasePredecessors(SU);
  721. SU->isScheduled = true;
  722. }
  723. /// Reinsert any remaining debug_values, just like the PostRA scheduler.
  724. void ScheduleDAGMI::placeDebugValues() {
  725. // If first instruction was a DBG_VALUE then put it back.
  726. if (FirstDbgValue) {
  727. BB->splice(RegionBegin, BB, FirstDbgValue);
  728. RegionBegin = FirstDbgValue;
  729. }
  730. for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
  731. DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
  732. std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
  733. MachineInstr *DbgValue = P.first;
  734. MachineBasicBlock::iterator OrigPrevMI = P.second;
  735. if (&*RegionBegin == DbgValue)
  736. ++RegionBegin;
  737. BB->splice(++OrigPrevMI, BB, DbgValue);
  738. if (OrigPrevMI == std::prev(RegionEnd))
  739. RegionEnd = DbgValue;
  740. }
  741. DbgValues.clear();
  742. FirstDbgValue = nullptr;
  743. }
  744. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  745. LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
  746. for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
  747. if (SUnit *SU = getSUnit(&(*MI)))
  748. SU->dump(this);
  749. else
  750. dbgs() << "Missing SUnit\n";
  751. }
  752. }
  753. #endif
  754. //===----------------------------------------------------------------------===//
  755. // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
  756. // preservation.
  757. //===----------------------------------------------------------------------===//
  758. ScheduleDAGMILive::~ScheduleDAGMILive() {
  759. delete DFSResult;
  760. }
  761. void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
  762. const MachineInstr &MI = *SU.getInstr();
  763. for (const MachineOperand &MO : MI.operands()) {
  764. if (!MO.isReg())
  765. continue;
  766. if (!MO.readsReg())
  767. continue;
  768. if (TrackLaneMasks && !MO.isUse())
  769. continue;
  770. unsigned Reg = MO.getReg();
  771. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  772. continue;
  773. // Ignore re-defs.
  774. if (TrackLaneMasks) {
  775. bool FoundDef = false;
  776. for (const MachineOperand &MO2 : MI.operands()) {
  777. if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
  778. FoundDef = true;
  779. break;
  780. }
  781. }
  782. if (FoundDef)
  783. continue;
  784. }
  785. // Record this local VReg use.
  786. VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
  787. for (; UI != VRegUses.end(); ++UI) {
  788. if (UI->SU == &SU)
  789. break;
  790. }
  791. if (UI == VRegUses.end())
  792. VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
  793. }
  794. }
  795. /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
  796. /// crossing a scheduling boundary. [begin, end) includes all instructions in
  797. /// the region, including the boundary itself and single-instruction regions
  798. /// that don't get scheduled.
  799. void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
  800. MachineBasicBlock::iterator begin,
  801. MachineBasicBlock::iterator end,
  802. unsigned regioninstrs)
  803. {
  804. // ScheduleDAGMI initializes SchedImpl's per-region policy.
  805. ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
  806. // For convenience remember the end of the liveness region.
  807. LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
  808. SUPressureDiffs.clear();
  809. ShouldTrackPressure = SchedImpl->shouldTrackPressure();
  810. ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
  811. assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
  812. "ShouldTrackLaneMasks requires ShouldTrackPressure");
  813. }
  814. // Setup the register pressure trackers for the top scheduled top and bottom
  815. // scheduled regions.
  816. void ScheduleDAGMILive::initRegPressure() {
  817. VRegUses.clear();
  818. VRegUses.setUniverse(MRI.getNumVirtRegs());
  819. for (SUnit &SU : SUnits)
  820. collectVRegUses(SU);
  821. TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
  822. ShouldTrackLaneMasks, false);
  823. BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
  824. ShouldTrackLaneMasks, false);
  825. // Close the RPTracker to finalize live ins.
  826. RPTracker.closeRegion();
  827. DEBUG(RPTracker.dump());
  828. // Initialize the live ins and live outs.
  829. TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
  830. BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
  831. // Close one end of the tracker so we can call
  832. // getMaxUpward/DownwardPressureDelta before advancing across any
  833. // instructions. This converts currently live regs into live ins/outs.
  834. TopRPTracker.closeTop();
  835. BotRPTracker.closeBottom();
  836. BotRPTracker.initLiveThru(RPTracker);
  837. if (!BotRPTracker.getLiveThru().empty()) {
  838. TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
  839. DEBUG(dbgs() << "Live Thru: ";
  840. dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
  841. };
  842. // For each live out vreg reduce the pressure change associated with other
  843. // uses of the same vreg below the live-out reaching def.
  844. updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
  845. // Account for liveness generated by the region boundary.
  846. if (LiveRegionEnd != RegionEnd) {
  847. SmallVector<RegisterMaskPair, 8> LiveUses;
  848. BotRPTracker.recede(&LiveUses);
  849. updatePressureDiffs(LiveUses);
  850. }
  851. DEBUG(
  852. dbgs() << "Top Pressure:\n";
  853. dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
  854. dbgs() << "Bottom Pressure:\n";
  855. dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
  856. );
  857. assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
  858. // Cache the list of excess pressure sets in this region. This will also track
  859. // the max pressure in the scheduled code for these sets.
  860. RegionCriticalPSets.clear();
  861. const std::vector<unsigned> &RegionPressure =
  862. RPTracker.getPressure().MaxSetPressure;
  863. for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
  864. unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
  865. if (RegionPressure[i] > Limit) {
  866. DEBUG(dbgs() << TRI->getRegPressureSetName(i)
  867. << " Limit " << Limit
  868. << " Actual " << RegionPressure[i] << "\n");
  869. RegionCriticalPSets.push_back(PressureChange(i));
  870. }
  871. }
  872. DEBUG(dbgs() << "Excess PSets: ";
  873. for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
  874. dbgs() << TRI->getRegPressureSetName(
  875. RegionCriticalPSets[i].getPSet()) << " ";
  876. dbgs() << "\n");
  877. }
  878. void ScheduleDAGMILive::
  879. updateScheduledPressure(const SUnit *SU,
  880. const std::vector<unsigned> &NewMaxPressure) {
  881. const PressureDiff &PDiff = getPressureDiff(SU);
  882. unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
  883. for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
  884. I != E; ++I) {
  885. if (!I->isValid())
  886. break;
  887. unsigned ID = I->getPSet();
  888. while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
  889. ++CritIdx;
  890. if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
  891. if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
  892. && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
  893. RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
  894. }
  895. unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
  896. if (NewMaxPressure[ID] >= Limit - 2) {
  897. DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
  898. << NewMaxPressure[ID]
  899. << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
  900. << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
  901. }
  902. }
  903. }
  904. /// Update the PressureDiff array for liveness after scheduling this
  905. /// instruction.
  906. void ScheduleDAGMILive::updatePressureDiffs(
  907. ArrayRef<RegisterMaskPair> LiveUses) {
  908. for (const RegisterMaskPair &P : LiveUses) {
  909. unsigned Reg = P.RegUnit;
  910. /// FIXME: Currently assuming single-use physregs.
  911. if (!TRI->isVirtualRegister(Reg))
  912. continue;
  913. if (ShouldTrackLaneMasks) {
  914. // If the register has just become live then other uses won't change
  915. // this fact anymore => decrement pressure.
  916. // If the register has just become dead then other uses make it come
  917. // back to life => increment pressure.
  918. bool Decrement = P.LaneMask.any();
  919. for (const VReg2SUnit &V2SU
  920. : make_range(VRegUses.find(Reg), VRegUses.end())) {
  921. SUnit &SU = *V2SU.SU;
  922. if (SU.isScheduled || &SU == &ExitSU)
  923. continue;
  924. PressureDiff &PDiff = getPressureDiff(&SU);
  925. PDiff.addPressureChange(Reg, Decrement, &MRI);
  926. DEBUG(
  927. dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
  928. << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
  929. << ' ' << *SU.getInstr();
  930. dbgs() << " to ";
  931. PDiff.dump(*TRI);
  932. );
  933. }
  934. } else {
  935. assert(P.LaneMask.any());
  936. DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
  937. // This may be called before CurrentBottom has been initialized. However,
  938. // BotRPTracker must have a valid position. We want the value live into the
  939. // instruction or live out of the block, so ask for the previous
  940. // instruction's live-out.
  941. const LiveInterval &LI = LIS->getInterval(Reg);
  942. VNInfo *VNI;
  943. MachineBasicBlock::const_iterator I =
  944. nextIfDebug(BotRPTracker.getPos(), BB->end());
  945. if (I == BB->end())
  946. VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
  947. else {
  948. LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
  949. VNI = LRQ.valueIn();
  950. }
  951. // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
  952. assert(VNI && "No live value at use.");
  953. for (const VReg2SUnit &V2SU
  954. : make_range(VRegUses.find(Reg), VRegUses.end())) {
  955. SUnit *SU = V2SU.SU;
  956. // If this use comes before the reaching def, it cannot be a last use,
  957. // so decrease its pressure change.
  958. if (!SU->isScheduled && SU != &ExitSU) {
  959. LiveQueryResult LRQ =
  960. LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
  961. if (LRQ.valueIn() == VNI) {
  962. PressureDiff &PDiff = getPressureDiff(SU);
  963. PDiff.addPressureChange(Reg, true, &MRI);
  964. DEBUG(
  965. dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
  966. << *SU->getInstr();
  967. dbgs() << " to ";
  968. PDiff.dump(*TRI);
  969. );
  970. }
  971. }
  972. }
  973. }
  974. }
  975. }
  976. /// schedule - Called back from MachineScheduler::runOnMachineFunction
  977. /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
  978. /// only includes instructions that have DAG nodes, not scheduling boundaries.
  979. ///
  980. /// This is a skeletal driver, with all the functionality pushed into helpers,
  981. /// so that it can be easily extended by experimental schedulers. Generally,
  982. /// implementing MachineSchedStrategy should be sufficient to implement a new
  983. /// scheduling algorithm. However, if a scheduler further subclasses
  984. /// ScheduleDAGMILive then it will want to override this virtual method in order
  985. /// to update any specialized state.
  986. void ScheduleDAGMILive::schedule() {
  987. DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
  988. DEBUG(SchedImpl->dumpPolicy());
  989. buildDAGWithRegPressure();
  990. Topo.InitDAGTopologicalSorting();
  991. postprocessDAG();
  992. SmallVector<SUnit*, 8> TopRoots, BotRoots;
  993. findRootsAndBiasEdges(TopRoots, BotRoots);
  994. // Initialize the strategy before modifying the DAG.
  995. // This may initialize a DFSResult to be used for queue priority.
  996. SchedImpl->initialize(this);
  997. DEBUG(
  998. if (EntrySU.getInstr() != nullptr)
  999. EntrySU.dumpAll(this);
  1000. for (const SUnit &SU : SUnits) {
  1001. SU.dumpAll(this);
  1002. if (ShouldTrackPressure) {
  1003. dbgs() << " Pressure Diff : ";
  1004. getPressureDiff(&SU).dump(*TRI);
  1005. }
  1006. dbgs() << " Single Issue : ";
  1007. if (SchedModel.mustBeginGroup(SU.getInstr()) &&
  1008. SchedModel.mustEndGroup(SU.getInstr()))
  1009. dbgs() << "true;";
  1010. else
  1011. dbgs() << "false;";
  1012. dbgs() << '\n';
  1013. }
  1014. if (ExitSU.getInstr() != nullptr)
  1015. ExitSU.dumpAll(this);
  1016. );
  1017. if (ViewMISchedDAGs) viewGraph();
  1018. // Initialize ready queues now that the DAG and priority data are finalized.
  1019. initQueues(TopRoots, BotRoots);
  1020. bool IsTopNode = false;
  1021. while (true) {
  1022. DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
  1023. SUnit *SU = SchedImpl->pickNode(IsTopNode);
  1024. if (!SU) break;
  1025. assert(!SU->isScheduled && "Node already scheduled");
  1026. if (!checkSchedLimit())
  1027. break;
  1028. scheduleMI(SU, IsTopNode);
  1029. if (DFSResult) {
  1030. unsigned SubtreeID = DFSResult->getSubtreeID(SU);
  1031. if (!ScheduledTrees.test(SubtreeID)) {
  1032. ScheduledTrees.set(SubtreeID);
  1033. DFSResult->scheduleTree(SubtreeID);
  1034. SchedImpl->scheduleTree(SubtreeID);
  1035. }
  1036. }
  1037. // Notify the scheduling strategy after updating the DAG.
  1038. SchedImpl->schedNode(SU, IsTopNode);
  1039. updateQueues(SU, IsTopNode);
  1040. }
  1041. assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
  1042. placeDebugValues();
  1043. DEBUG({
  1044. unsigned BBNum = begin()->getParent()->getNumber();
  1045. dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
  1046. dumpSchedule();
  1047. dbgs() << '\n';
  1048. });
  1049. }
  1050. /// Build the DAG and setup three register pressure trackers.
  1051. void ScheduleDAGMILive::buildDAGWithRegPressure() {
  1052. if (!ShouldTrackPressure) {
  1053. RPTracker.reset();
  1054. RegionCriticalPSets.clear();
  1055. buildSchedGraph(AA);
  1056. return;
  1057. }
  1058. // Initialize the register pressure tracker used by buildSchedGraph.
  1059. RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
  1060. ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
  1061. // Account for liveness generate by the region boundary.
  1062. if (LiveRegionEnd != RegionEnd)
  1063. RPTracker.recede();
  1064. // Build the DAG, and compute current register pressure.
  1065. buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
  1066. // Initialize top/bottom trackers after computing region pressure.
  1067. initRegPressure();
  1068. }
  1069. void ScheduleDAGMILive::computeDFSResult() {
  1070. if (!DFSResult)
  1071. DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
  1072. DFSResult->clear();
  1073. ScheduledTrees.clear();
  1074. DFSResult->resize(SUnits.size());
  1075. DFSResult->compute(SUnits);
  1076. ScheduledTrees.resize(DFSResult->getNumSubtrees());
  1077. }
  1078. /// Compute the max cyclic critical path through the DAG. The scheduling DAG
  1079. /// only provides the critical path for single block loops. To handle loops that
  1080. /// span blocks, we could use the vreg path latencies provided by
  1081. /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
  1082. /// available for use in the scheduler.
  1083. ///
  1084. /// The cyclic path estimation identifies a def-use pair that crosses the back
  1085. /// edge and considers the depth and height of the nodes. For example, consider
  1086. /// the following instruction sequence where each instruction has unit latency
  1087. /// and defines an epomymous virtual register:
  1088. ///
  1089. /// a->b(a,c)->c(b)->d(c)->exit
  1090. ///
  1091. /// The cyclic critical path is a two cycles: b->c->b
  1092. /// The acyclic critical path is four cycles: a->b->c->d->exit
  1093. /// LiveOutHeight = height(c) = len(c->d->exit) = 2
  1094. /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
  1095. /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
  1096. /// LiveInDepth = depth(b) = len(a->b) = 1
  1097. ///
  1098. /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
  1099. /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
  1100. /// CyclicCriticalPath = min(2, 2) = 2
  1101. ///
  1102. /// This could be relevant to PostRA scheduling, but is currently implemented
  1103. /// assuming LiveIntervals.
  1104. unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
  1105. // This only applies to single block loop.
  1106. if (!BB->isSuccessor(BB))
  1107. return 0;
  1108. unsigned MaxCyclicLatency = 0;
  1109. // Visit each live out vreg def to find def/use pairs that cross iterations.
  1110. for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
  1111. unsigned Reg = P.RegUnit;
  1112. if (!TRI->isVirtualRegister(Reg))
  1113. continue;
  1114. const LiveInterval &LI = LIS->getInterval(Reg);
  1115. const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
  1116. if (!DefVNI)
  1117. continue;
  1118. MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
  1119. const SUnit *DefSU = getSUnit(DefMI);
  1120. if (!DefSU)
  1121. continue;
  1122. unsigned LiveOutHeight = DefSU->getHeight();
  1123. unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
  1124. // Visit all local users of the vreg def.
  1125. for (const VReg2SUnit &V2SU
  1126. : make_range(VRegUses.find(Reg), VRegUses.end())) {
  1127. SUnit *SU = V2SU.SU;
  1128. if (SU == &ExitSU)
  1129. continue;
  1130. // Only consider uses of the phi.
  1131. LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
  1132. if (!LRQ.valueIn()->isPHIDef())
  1133. continue;
  1134. // Assume that a path spanning two iterations is a cycle, which could
  1135. // overestimate in strange cases. This allows cyclic latency to be
  1136. // estimated as the minimum slack of the vreg's depth or height.
  1137. unsigned CyclicLatency = 0;
  1138. if (LiveOutDepth > SU->getDepth())
  1139. CyclicLatency = LiveOutDepth - SU->getDepth();
  1140. unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
  1141. if (LiveInHeight > LiveOutHeight) {
  1142. if (LiveInHeight - LiveOutHeight < CyclicLatency)
  1143. CyclicLatency = LiveInHeight - LiveOutHeight;
  1144. } else
  1145. CyclicLatency = 0;
  1146. DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
  1147. << SU->NodeNum << ") = " << CyclicLatency << "c\n");
  1148. if (CyclicLatency > MaxCyclicLatency)
  1149. MaxCyclicLatency = CyclicLatency;
  1150. }
  1151. }
  1152. DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
  1153. return MaxCyclicLatency;
  1154. }
  1155. /// Release ExitSU predecessors and setup scheduler queues. Re-position
  1156. /// the Top RP tracker in case the region beginning has changed.
  1157. void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
  1158. ArrayRef<SUnit*> BotRoots) {
  1159. ScheduleDAGMI::initQueues(TopRoots, BotRoots);
  1160. if (ShouldTrackPressure) {
  1161. assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
  1162. TopRPTracker.setPos(CurrentTop);
  1163. }
  1164. }
  1165. /// Move an instruction and update register pressure.
  1166. void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
  1167. // Move the instruction to its new location in the instruction stream.
  1168. MachineInstr *MI = SU->getInstr();
  1169. if (IsTopNode) {
  1170. assert(SU->isTopReady() && "node still has unscheduled dependencies");
  1171. if (&*CurrentTop == MI)
  1172. CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
  1173. else {
  1174. moveInstruction(MI, CurrentTop);
  1175. TopRPTracker.setPos(MI);
  1176. }
  1177. if (ShouldTrackPressure) {
  1178. // Update top scheduled pressure.
  1179. RegisterOperands RegOpers;
  1180. RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
  1181. if (ShouldTrackLaneMasks) {
  1182. // Adjust liveness and add missing dead+read-undef flags.
  1183. SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
  1184. RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
  1185. } else {
  1186. // Adjust for missing dead-def flags.
  1187. RegOpers.detectDeadDefs(*MI, *LIS);
  1188. }
  1189. TopRPTracker.advance(RegOpers);
  1190. assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
  1191. DEBUG(
  1192. dbgs() << "Top Pressure:\n";
  1193. dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
  1194. );
  1195. updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
  1196. }
  1197. } else {
  1198. assert(SU->isBottomReady() && "node still has unscheduled dependencies");
  1199. MachineBasicBlock::iterator priorII =
  1200. priorNonDebug(CurrentBottom, CurrentTop);
  1201. if (&*priorII == MI)
  1202. CurrentBottom = priorII;
  1203. else {
  1204. if (&*CurrentTop == MI) {
  1205. CurrentTop = nextIfDebug(++CurrentTop, priorII);
  1206. TopRPTracker.setPos(CurrentTop);
  1207. }
  1208. moveInstruction(MI, CurrentBottom);
  1209. CurrentBottom = MI;
  1210. }
  1211. if (ShouldTrackPressure) {
  1212. RegisterOperands RegOpers;
  1213. RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
  1214. if (ShouldTrackLaneMasks) {
  1215. // Adjust liveness and add missing dead+read-undef flags.
  1216. SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
  1217. RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
  1218. } else {
  1219. // Adjust for missing dead-def flags.
  1220. RegOpers.detectDeadDefs(*MI, *LIS);
  1221. }
  1222. BotRPTracker.recedeSkipDebugValues();
  1223. SmallVector<RegisterMaskPair, 8> LiveUses;
  1224. BotRPTracker.recede(RegOpers, &LiveUses);
  1225. assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
  1226. DEBUG(
  1227. dbgs() << "Bottom Pressure:\n";
  1228. dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
  1229. );
  1230. updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
  1231. updatePressureDiffs(LiveUses);
  1232. }
  1233. }
  1234. }
  1235. //===----------------------------------------------------------------------===//
  1236. // BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
  1237. //===----------------------------------------------------------------------===//
  1238. namespace {
  1239. /// \brief Post-process the DAG to create cluster edges between neighboring
  1240. /// loads or between neighboring stores.
  1241. class BaseMemOpClusterMutation : public ScheduleDAGMutation {
  1242. struct MemOpInfo {
  1243. SUnit *SU;
  1244. unsigned BaseReg;
  1245. int64_t Offset;
  1246. MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
  1247. : SU(su), BaseReg(reg), Offset(ofs) {}
  1248. bool operator<(const MemOpInfo&RHS) const {
  1249. return std::tie(BaseReg, Offset, SU->NodeNum) <
  1250. std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
  1251. }
  1252. };
  1253. const TargetInstrInfo *TII;
  1254. const TargetRegisterInfo *TRI;
  1255. bool IsLoad;
  1256. public:
  1257. BaseMemOpClusterMutation(const TargetInstrInfo *tii,
  1258. const TargetRegisterInfo *tri, bool IsLoad)
  1259. : TII(tii), TRI(tri), IsLoad(IsLoad) {}
  1260. void apply(ScheduleDAGInstrs *DAGInstrs) override;
  1261. protected:
  1262. void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
  1263. };
  1264. class StoreClusterMutation : public BaseMemOpClusterMutation {
  1265. public:
  1266. StoreClusterMutation(const TargetInstrInfo *tii,
  1267. const TargetRegisterInfo *tri)
  1268. : BaseMemOpClusterMutation(tii, tri, false) {}
  1269. };
  1270. class LoadClusterMutation : public BaseMemOpClusterMutation {
  1271. public:
  1272. LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
  1273. : BaseMemOpClusterMutation(tii, tri, true) {}
  1274. };
  1275. } // end anonymous namespace
  1276. namespace llvm {
  1277. std::unique_ptr<ScheduleDAGMutation>
  1278. createLoadClusterDAGMutation(const TargetInstrInfo *TII,
  1279. const TargetRegisterInfo *TRI) {
  1280. return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
  1281. : nullptr;
  1282. }
  1283. std::unique_ptr<ScheduleDAGMutation>
  1284. createStoreClusterDAGMutation(const TargetInstrInfo *TII,
  1285. const TargetRegisterInfo *TRI) {
  1286. return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
  1287. : nullptr;
  1288. }
  1289. } // end namespace llvm
  1290. void BaseMemOpClusterMutation::clusterNeighboringMemOps(
  1291. ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
  1292. SmallVector<MemOpInfo, 32> MemOpRecords;
  1293. for (unsigned Idx = 0, End = MemOps.size(); Idx != End; ++Idx) {
  1294. SUnit *SU = MemOps[Idx];
  1295. unsigned BaseReg;
  1296. int64_t Offset;
  1297. if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
  1298. MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
  1299. }
  1300. if (MemOpRecords.size() < 2)
  1301. return;
  1302. std::sort(MemOpRecords.begin(), MemOpRecords.end());
  1303. unsigned ClusterLength = 1;
  1304. for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
  1305. if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) {
  1306. ClusterLength = 1;
  1307. continue;
  1308. }
  1309. SUnit *SUa = MemOpRecords[Idx].SU;
  1310. SUnit *SUb = MemOpRecords[Idx+1].SU;
  1311. if (TII->shouldClusterMemOps(*SUa->getInstr(), *SUb->getInstr(),
  1312. ClusterLength) &&
  1313. DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
  1314. DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
  1315. << SUb->NodeNum << ")\n");
  1316. // Copy successor edges from SUa to SUb. Interleaving computation
  1317. // dependent on SUa can prevent load combining due to register reuse.
  1318. // Predecessor edges do not need to be copied from SUb to SUa since nearby
  1319. // loads should have effectively the same inputs.
  1320. for (SUnit::const_succ_iterator
  1321. SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
  1322. if (SI->getSUnit() == SUb)
  1323. continue;
  1324. DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
  1325. DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
  1326. }
  1327. ++ClusterLength;
  1328. } else
  1329. ClusterLength = 1;
  1330. }
  1331. }
  1332. /// \brief Callback from DAG postProcessing to create cluster edges for loads.
  1333. void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
  1334. ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
  1335. // Map DAG NodeNum to store chain ID.
  1336. DenseMap<unsigned, unsigned> StoreChainIDs;
  1337. // Map each store chain to a set of dependent MemOps.
  1338. SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
  1339. for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
  1340. SUnit *SU = &DAG->SUnits[Idx];
  1341. if ((IsLoad && !SU->getInstr()->mayLoad()) ||
  1342. (!IsLoad && !SU->getInstr()->mayStore()))
  1343. continue;
  1344. unsigned ChainPredID = DAG->SUnits.size();
  1345. for (SUnit::const_pred_iterator
  1346. PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
  1347. if (PI->isCtrl()) {
  1348. ChainPredID = PI->getSUnit()->NodeNum;
  1349. break;
  1350. }
  1351. }
  1352. // Check if this chain-like pred has been seen
  1353. // before. ChainPredID==MaxNodeID at the top of the schedule.
  1354. unsigned NumChains = StoreChainDependents.size();
  1355. std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
  1356. StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
  1357. if (Result.second)
  1358. StoreChainDependents.resize(NumChains + 1);
  1359. StoreChainDependents[Result.first->second].push_back(SU);
  1360. }
  1361. // Iterate over the store chains.
  1362. for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
  1363. clusterNeighboringMemOps(StoreChainDependents[Idx], DAG);
  1364. }
  1365. //===----------------------------------------------------------------------===//
  1366. // CopyConstrain - DAG post-processing to encourage copy elimination.
  1367. //===----------------------------------------------------------------------===//
  1368. namespace {
  1369. /// \brief Post-process the DAG to create weak edges from all uses of a copy to
  1370. /// the one use that defines the copy's source vreg, most likely an induction
  1371. /// variable increment.
  1372. class CopyConstrain : public ScheduleDAGMutation {
  1373. // Transient state.
  1374. SlotIndex RegionBeginIdx;
  1375. // RegionEndIdx is the slot index of the last non-debug instruction in the
  1376. // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
  1377. SlotIndex RegionEndIdx;
  1378. public:
  1379. CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
  1380. void apply(ScheduleDAGInstrs *DAGInstrs) override;
  1381. protected:
  1382. void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
  1383. };
  1384. } // end anonymous namespace
  1385. namespace llvm {
  1386. std::unique_ptr<ScheduleDAGMutation>
  1387. createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
  1388. const TargetRegisterInfo *TRI) {
  1389. return llvm::make_unique<CopyConstrain>(TII, TRI);
  1390. }
  1391. } // end namespace llvm
  1392. /// constrainLocalCopy handles two possibilities:
  1393. /// 1) Local src:
  1394. /// I0: = dst
  1395. /// I1: src = ...
  1396. /// I2: = dst
  1397. /// I3: dst = src (copy)
  1398. /// (create pred->succ edges I0->I1, I2->I1)
  1399. ///
  1400. /// 2) Local copy:
  1401. /// I0: dst = src (copy)
  1402. /// I1: = dst
  1403. /// I2: src = ...
  1404. /// I3: = dst
  1405. /// (create pred->succ edges I1->I2, I3->I2)
  1406. ///
  1407. /// Although the MachineScheduler is currently constrained to single blocks,
  1408. /// this algorithm should handle extended blocks. An EBB is a set of
  1409. /// contiguously numbered blocks such that the previous block in the EBB is
  1410. /// always the single predecessor.
  1411. void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
  1412. LiveIntervals *LIS = DAG->getLIS();
  1413. MachineInstr *Copy = CopySU->getInstr();
  1414. // Check for pure vreg copies.
  1415. const MachineOperand &SrcOp = Copy->getOperand(1);
  1416. unsigned SrcReg = SrcOp.getReg();
  1417. if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
  1418. return;
  1419. const MachineOperand &DstOp = Copy->getOperand(0);
  1420. unsigned DstReg = DstOp.getReg();
  1421. if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
  1422. return;
  1423. // Check if either the dest or source is local. If it's live across a back
  1424. // edge, it's not local. Note that if both vregs are live across the back
  1425. // edge, we cannot successfully contrain the copy without cyclic scheduling.
  1426. // If both the copy's source and dest are local live intervals, then we
  1427. // should treat the dest as the global for the purpose of adding
  1428. // constraints. This adds edges from source's other uses to the copy.
  1429. unsigned LocalReg = SrcReg;
  1430. unsigned GlobalReg = DstReg;
  1431. LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
  1432. if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
  1433. LocalReg = DstReg;
  1434. GlobalReg = SrcReg;
  1435. LocalLI = &LIS->getInterval(LocalReg);
  1436. if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
  1437. return;
  1438. }
  1439. LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
  1440. // Find the global segment after the start of the local LI.
  1441. LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
  1442. // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
  1443. // local live range. We could create edges from other global uses to the local
  1444. // start, but the coalescer should have already eliminated these cases, so
  1445. // don't bother dealing with it.
  1446. if (GlobalSegment == GlobalLI->end())
  1447. return;
  1448. // If GlobalSegment is killed at the LocalLI->start, the call to find()
  1449. // returned the next global segment. But if GlobalSegment overlaps with
  1450. // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
  1451. // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
  1452. if (GlobalSegment->contains(LocalLI->beginIndex()))
  1453. ++GlobalSegment;
  1454. if (GlobalSegment == GlobalLI->end())
  1455. return;
  1456. // Check if GlobalLI contains a hole in the vicinity of LocalLI.
  1457. if (GlobalSegment != GlobalLI->begin()) {
  1458. // Two address defs have no hole.
  1459. if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
  1460. GlobalSegment->start)) {
  1461. return;
  1462. }
  1463. // If the prior global segment may be defined by the same two-address
  1464. // instruction that also defines LocalLI, then can't make a hole here.
  1465. if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
  1466. LocalLI->beginIndex())) {
  1467. return;
  1468. }
  1469. // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
  1470. // it would be a disconnected component in the live range.
  1471. assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
  1472. "Disconnected LRG within the scheduling region.");
  1473. }
  1474. MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
  1475. if (!GlobalDef)
  1476. return;
  1477. SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
  1478. if (!GlobalSU)
  1479. return;
  1480. // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
  1481. // constraining the uses of the last local def to precede GlobalDef.
  1482. SmallVector<SUnit*,8> LocalUses;
  1483. const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
  1484. MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
  1485. SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
  1486. for (SUnit::const_succ_iterator
  1487. I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
  1488. I != E; ++I) {
  1489. if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
  1490. continue;
  1491. if (I->getSUnit() == GlobalSU)
  1492. continue;
  1493. if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
  1494. return;
  1495. LocalUses.push_back(I->getSUnit());
  1496. }
  1497. // Open the top of the GlobalLI hole by constraining any earlier global uses
  1498. // to precede the start of LocalLI.
  1499. SmallVector<SUnit*,8> GlobalUses;
  1500. MachineInstr *FirstLocalDef =
  1501. LIS->getInstructionFromIndex(LocalLI->beginIndex());
  1502. SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
  1503. for (SUnit::const_pred_iterator
  1504. I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
  1505. if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
  1506. continue;
  1507. if (I->getSUnit() == FirstLocalSU)
  1508. continue;
  1509. if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
  1510. return;
  1511. GlobalUses.push_back(I->getSUnit());
  1512. }
  1513. DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
  1514. // Add the weak edges.
  1515. for (SmallVectorImpl<SUnit*>::const_iterator
  1516. I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
  1517. DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
  1518. << GlobalSU->NodeNum << ")\n");
  1519. DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
  1520. }
  1521. for (SmallVectorImpl<SUnit*>::const_iterator
  1522. I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
  1523. DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
  1524. << FirstLocalSU->NodeNum << ")\n");
  1525. DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
  1526. }
  1527. }
  1528. /// \brief Callback from DAG postProcessing to create weak edges to encourage
  1529. /// copy elimination.
  1530. void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
  1531. ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
  1532. assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
  1533. MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
  1534. if (FirstPos == DAG->end())
  1535. return;
  1536. RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
  1537. RegionEndIdx = DAG->getLIS()->getInstructionIndex(
  1538. *priorNonDebug(DAG->end(), DAG->begin()));
  1539. for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
  1540. SUnit *SU = &DAG->SUnits[Idx];
  1541. if (!SU->getInstr()->isCopy())
  1542. continue;
  1543. constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
  1544. }
  1545. }
  1546. //===----------------------------------------------------------------------===//
  1547. // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
  1548. // and possibly other custom schedulers.
  1549. //===----------------------------------------------------------------------===//
  1550. static const unsigned InvalidCycle = ~0U;
  1551. SchedBoundary::~SchedBoundary() { delete HazardRec; }
  1552. void SchedBoundary::reset() {
  1553. // A new HazardRec is created for each DAG and owned by SchedBoundary.
  1554. // Destroying and reconstructing it is very expensive though. So keep
  1555. // invalid, placeholder HazardRecs.
  1556. if (HazardRec && HazardRec->isEnabled()) {
  1557. delete HazardRec;
  1558. HazardRec = nullptr;
  1559. }
  1560. Available.clear();
  1561. Pending.clear();
  1562. CheckPending = false;
  1563. CurrCycle = 0;
  1564. CurrMOps = 0;
  1565. MinReadyCycle = std::numeric_limits<unsigned>::max();
  1566. ExpectedLatency = 0;
  1567. DependentLatency = 0;
  1568. RetiredMOps = 0;
  1569. MaxExecutedResCount = 0;
  1570. ZoneCritResIdx = 0;
  1571. IsResourceLimited = false;
  1572. ReservedCycles.clear();
  1573. #ifndef NDEBUG
  1574. // Track the maximum number of stall cycles that could arise either from the
  1575. // latency of a DAG edge or the number of cycles that a processor resource is
  1576. // reserved (SchedBoundary::ReservedCycles).
  1577. MaxObservedStall = 0;
  1578. #endif
  1579. // Reserve a zero-count for invalid CritResIdx.
  1580. ExecutedResCounts.resize(1);
  1581. assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
  1582. }
  1583. void SchedRemainder::
  1584. init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
  1585. reset();
  1586. if (!SchedModel->hasInstrSchedModel())
  1587. return;
  1588. RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
  1589. for (std::vector<SUnit>::iterator
  1590. I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
  1591. const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
  1592. RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
  1593. * SchedModel->getMicroOpFactor();
  1594. for (TargetSchedModel::ProcResIter
  1595. PI = SchedModel->getWriteProcResBegin(SC),
  1596. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1597. unsigned PIdx = PI->ProcResourceIdx;
  1598. unsigned Factor = SchedModel->getResourceFactor(PIdx);
  1599. RemainingCounts[PIdx] += (Factor * PI->Cycles);
  1600. }
  1601. }
  1602. }
  1603. void SchedBoundary::
  1604. init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
  1605. reset();
  1606. DAG = dag;
  1607. SchedModel = smodel;
  1608. Rem = rem;
  1609. if (SchedModel->hasInstrSchedModel()) {
  1610. ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
  1611. ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
  1612. }
  1613. }
  1614. /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
  1615. /// these "soft stalls" differently than the hard stall cycles based on CPU
  1616. /// resources and computed by checkHazard(). A fully in-order model
  1617. /// (MicroOpBufferSize==0) will not make use of this since instructions are not
  1618. /// available for scheduling until they are ready. However, a weaker in-order
  1619. /// model may use this for heuristics. For example, if a processor has in-order
  1620. /// behavior when reading certain resources, this may come into play.
  1621. unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
  1622. if (!SU->isUnbuffered)
  1623. return 0;
  1624. unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
  1625. if (ReadyCycle > CurrCycle)
  1626. return ReadyCycle - CurrCycle;
  1627. return 0;
  1628. }
  1629. /// Compute the next cycle at which the given processor resource can be
  1630. /// scheduled.
  1631. unsigned SchedBoundary::
  1632. getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
  1633. unsigned NextUnreserved = ReservedCycles[PIdx];
  1634. // If this resource has never been used, always return cycle zero.
  1635. if (NextUnreserved == InvalidCycle)
  1636. return 0;
  1637. // For bottom-up scheduling add the cycles needed for the current operation.
  1638. if (!isTop())
  1639. NextUnreserved += Cycles;
  1640. return NextUnreserved;
  1641. }
  1642. /// Does this SU have a hazard within the current instruction group.
  1643. ///
  1644. /// The scheduler supports two modes of hazard recognition. The first is the
  1645. /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
  1646. /// supports highly complicated in-order reservation tables
  1647. /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
  1648. ///
  1649. /// The second is a streamlined mechanism that checks for hazards based on
  1650. /// simple counters that the scheduler itself maintains. It explicitly checks
  1651. /// for instruction dispatch limitations, including the number of micro-ops that
  1652. /// can dispatch per cycle.
  1653. ///
  1654. /// TODO: Also check whether the SU must start a new group.
  1655. bool SchedBoundary::checkHazard(SUnit *SU) {
  1656. if (HazardRec->isEnabled()
  1657. && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
  1658. return true;
  1659. }
  1660. unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
  1661. if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
  1662. DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
  1663. << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
  1664. return true;
  1665. }
  1666. if (CurrMOps > 0 &&
  1667. ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
  1668. (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
  1669. DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must "
  1670. << (isTop()? "begin" : "end") << " group\n");
  1671. return true;
  1672. }
  1673. if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
  1674. const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
  1675. for (TargetSchedModel::ProcResIter
  1676. PI = SchedModel->getWriteProcResBegin(SC),
  1677. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1678. unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles);
  1679. if (NRCycle > CurrCycle) {
  1680. #ifndef NDEBUG
  1681. MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
  1682. #endif
  1683. DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
  1684. << SchedModel->getResourceName(PI->ProcResourceIdx)
  1685. << "=" << NRCycle << "c\n");
  1686. return true;
  1687. }
  1688. }
  1689. }
  1690. return false;
  1691. }
  1692. // Find the unscheduled node in ReadySUs with the highest latency.
  1693. unsigned SchedBoundary::
  1694. findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
  1695. SUnit *LateSU = nullptr;
  1696. unsigned RemLatency = 0;
  1697. for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
  1698. I != E; ++I) {
  1699. unsigned L = getUnscheduledLatency(*I);
  1700. if (L > RemLatency) {
  1701. RemLatency = L;
  1702. LateSU = *I;
  1703. }
  1704. }
  1705. if (LateSU) {
  1706. DEBUG(dbgs() << Available.getName() << " RemLatency SU("
  1707. << LateSU->NodeNum << ") " << RemLatency << "c\n");
  1708. }
  1709. return RemLatency;
  1710. }
  1711. // Count resources in this zone and the remaining unscheduled
  1712. // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
  1713. // resource index, or zero if the zone is issue limited.
  1714. unsigned SchedBoundary::
  1715. getOtherResourceCount(unsigned &OtherCritIdx) {
  1716. OtherCritIdx = 0;
  1717. if (!SchedModel->hasInstrSchedModel())
  1718. return 0;
  1719. unsigned OtherCritCount = Rem->RemIssueCount
  1720. + (RetiredMOps * SchedModel->getMicroOpFactor());
  1721. DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
  1722. << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
  1723. for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
  1724. PIdx != PEnd; ++PIdx) {
  1725. unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
  1726. if (OtherCount > OtherCritCount) {
  1727. OtherCritCount = OtherCount;
  1728. OtherCritIdx = PIdx;
  1729. }
  1730. }
  1731. if (OtherCritIdx) {
  1732. DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
  1733. << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
  1734. << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
  1735. }
  1736. return OtherCritCount;
  1737. }
  1738. void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
  1739. assert(SU->getInstr() && "Scheduled SUnit must have instr");
  1740. #ifndef NDEBUG
  1741. // ReadyCycle was been bumped up to the CurrCycle when this node was
  1742. // scheduled, but CurrCycle may have been eagerly advanced immediately after
  1743. // scheduling, so may now be greater than ReadyCycle.
  1744. if (ReadyCycle > CurrCycle)
  1745. MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
  1746. #endif
  1747. if (ReadyCycle < MinReadyCycle)
  1748. MinReadyCycle = ReadyCycle;
  1749. // Check for interlocks first. For the purpose of other heuristics, an
  1750. // instruction that cannot issue appears as if it's not in the ReadyQueue.
  1751. bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
  1752. if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
  1753. Available.size() >= ReadyListLimit)
  1754. Pending.push(SU);
  1755. else
  1756. Available.push(SU);
  1757. }
  1758. /// Move the boundary of scheduled code by one cycle.
  1759. void SchedBoundary::bumpCycle(unsigned NextCycle) {
  1760. if (SchedModel->getMicroOpBufferSize() == 0) {
  1761. assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
  1762. "MinReadyCycle uninitialized");
  1763. if (MinReadyCycle > NextCycle)
  1764. NextCycle = MinReadyCycle;
  1765. }
  1766. // Update the current micro-ops, which will issue in the next cycle.
  1767. unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
  1768. CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
  1769. // Decrement DependentLatency based on the next cycle.
  1770. if ((NextCycle - CurrCycle) > DependentLatency)
  1771. DependentLatency = 0;
  1772. else
  1773. DependentLatency -= (NextCycle - CurrCycle);
  1774. if (!HazardRec->isEnabled()) {
  1775. // Bypass HazardRec virtual calls.
  1776. CurrCycle = NextCycle;
  1777. } else {
  1778. // Bypass getHazardType calls in case of long latency.
  1779. for (; CurrCycle != NextCycle; ++CurrCycle) {
  1780. if (isTop())
  1781. HazardRec->AdvanceCycle();
  1782. else
  1783. HazardRec->RecedeCycle();
  1784. }
  1785. }
  1786. CheckPending = true;
  1787. unsigned LFactor = SchedModel->getLatencyFactor();
  1788. IsResourceLimited =
  1789. (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
  1790. > (int)LFactor;
  1791. DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
  1792. }
  1793. void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
  1794. ExecutedResCounts[PIdx] += Count;
  1795. if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
  1796. MaxExecutedResCount = ExecutedResCounts[PIdx];
  1797. }
  1798. /// Add the given processor resource to this scheduled zone.
  1799. ///
  1800. /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
  1801. /// during which this resource is consumed.
  1802. ///
  1803. /// \return the next cycle at which the instruction may execute without
  1804. /// oversubscribing resources.
  1805. unsigned SchedBoundary::
  1806. countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
  1807. unsigned Factor = SchedModel->getResourceFactor(PIdx);
  1808. unsigned Count = Factor * Cycles;
  1809. DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
  1810. << " +" << Cycles << "x" << Factor << "u\n");
  1811. // Update Executed resources counts.
  1812. incExecutedResources(PIdx, Count);
  1813. assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
  1814. Rem->RemainingCounts[PIdx] -= Count;
  1815. // Check if this resource exceeds the current critical resource. If so, it
  1816. // becomes the critical resource.
  1817. if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
  1818. ZoneCritResIdx = PIdx;
  1819. DEBUG(dbgs() << " *** Critical resource "
  1820. << SchedModel->getResourceName(PIdx) << ": "
  1821. << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
  1822. }
  1823. // For reserved resources, record the highest cycle using the resource.
  1824. unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
  1825. if (NextAvailable > CurrCycle) {
  1826. DEBUG(dbgs() << " Resource conflict: "
  1827. << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
  1828. << NextAvailable << "\n");
  1829. }
  1830. return NextAvailable;
  1831. }
  1832. /// Move the boundary of scheduled code by one SUnit.
  1833. void SchedBoundary::bumpNode(SUnit *SU) {
  1834. // Update the reservation table.
  1835. if (HazardRec->isEnabled()) {
  1836. if (!isTop() && SU->isCall) {
  1837. // Calls are scheduled with their preceding instructions. For bottom-up
  1838. // scheduling, clear the pipeline state before emitting.
  1839. HazardRec->Reset();
  1840. }
  1841. HazardRec->EmitInstruction(SU);
  1842. }
  1843. // checkHazard should prevent scheduling multiple instructions per cycle that
  1844. // exceed the issue width.
  1845. const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
  1846. unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
  1847. assert(
  1848. (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
  1849. "Cannot schedule this instruction's MicroOps in the current cycle.");
  1850. unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
  1851. DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
  1852. unsigned NextCycle = CurrCycle;
  1853. switch (SchedModel->getMicroOpBufferSize()) {
  1854. case 0:
  1855. assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
  1856. break;
  1857. case 1:
  1858. if (ReadyCycle > NextCycle) {
  1859. NextCycle = ReadyCycle;
  1860. DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
  1861. }
  1862. break;
  1863. default:
  1864. // We don't currently model the OOO reorder buffer, so consider all
  1865. // scheduled MOps to be "retired". We do loosely model in-order resource
  1866. // latency. If this instruction uses an in-order resource, account for any
  1867. // likely stall cycles.
  1868. if (SU->isUnbuffered && ReadyCycle > NextCycle)
  1869. NextCycle = ReadyCycle;
  1870. break;
  1871. }
  1872. RetiredMOps += IncMOps;
  1873. // Update resource counts and critical resource.
  1874. if (SchedModel->hasInstrSchedModel()) {
  1875. unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
  1876. assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
  1877. Rem->RemIssueCount -= DecRemIssue;
  1878. if (ZoneCritResIdx) {
  1879. // Scale scheduled micro-ops for comparing with the critical resource.
  1880. unsigned ScaledMOps =
  1881. RetiredMOps * SchedModel->getMicroOpFactor();
  1882. // If scaled micro-ops are now more than the previous critical resource by
  1883. // a full cycle, then micro-ops issue becomes critical.
  1884. if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
  1885. >= (int)SchedModel->getLatencyFactor()) {
  1886. ZoneCritResIdx = 0;
  1887. DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
  1888. << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
  1889. }
  1890. }
  1891. for (TargetSchedModel::ProcResIter
  1892. PI = SchedModel->getWriteProcResBegin(SC),
  1893. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1894. unsigned RCycle =
  1895. countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
  1896. if (RCycle > NextCycle)
  1897. NextCycle = RCycle;
  1898. }
  1899. if (SU->hasReservedResource) {
  1900. // For reserved resources, record the highest cycle using the resource.
  1901. // For top-down scheduling, this is the cycle in which we schedule this
  1902. // instruction plus the number of cycles the operations reserves the
  1903. // resource. For bottom-up is it simply the instruction's cycle.
  1904. for (TargetSchedModel::ProcResIter
  1905. PI = SchedModel->getWriteProcResBegin(SC),
  1906. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  1907. unsigned PIdx = PI->ProcResourceIdx;
  1908. if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
  1909. if (isTop()) {
  1910. ReservedCycles[PIdx] =
  1911. std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
  1912. }
  1913. else
  1914. ReservedCycles[PIdx] = NextCycle;
  1915. }
  1916. }
  1917. }
  1918. }
  1919. // Update ExpectedLatency and DependentLatency.
  1920. unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
  1921. unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
  1922. if (SU->getDepth() > TopLatency) {
  1923. TopLatency = SU->getDepth();
  1924. DEBUG(dbgs() << " " << Available.getName()
  1925. << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
  1926. }
  1927. if (SU->getHeight() > BotLatency) {
  1928. BotLatency = SU->getHeight();
  1929. DEBUG(dbgs() << " " << Available.getName()
  1930. << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
  1931. }
  1932. // If we stall for any reason, bump the cycle.
  1933. if (NextCycle > CurrCycle) {
  1934. bumpCycle(NextCycle);
  1935. } else {
  1936. // After updating ZoneCritResIdx and ExpectedLatency, check if we're
  1937. // resource limited. If a stall occurred, bumpCycle does this.
  1938. unsigned LFactor = SchedModel->getLatencyFactor();
  1939. IsResourceLimited =
  1940. (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
  1941. > (int)LFactor;
  1942. }
  1943. // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
  1944. // resets CurrMOps. Loop to handle instructions with more MOps than issue in
  1945. // one cycle. Since we commonly reach the max MOps here, opportunistically
  1946. // bump the cycle to avoid uselessly checking everything in the readyQ.
  1947. CurrMOps += IncMOps;
  1948. // Bump the cycle count for issue group constraints.
  1949. // This must be done after NextCycle has been adjust for all other stalls.
  1950. // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
  1951. // currCycle to X.
  1952. if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
  1953. (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
  1954. DEBUG(dbgs() << " Bump cycle to "
  1955. << (isTop() ? "end" : "begin") << " group\n");
  1956. bumpCycle(++NextCycle);
  1957. }
  1958. while (CurrMOps >= SchedModel->getIssueWidth()) {
  1959. DEBUG(dbgs() << " *** Max MOps " << CurrMOps
  1960. << " at cycle " << CurrCycle << '\n');
  1961. bumpCycle(++NextCycle);
  1962. }
  1963. DEBUG(dumpScheduledState());
  1964. }
  1965. /// Release pending ready nodes in to the available queue. This makes them
  1966. /// visible to heuristics.
  1967. void SchedBoundary::releasePending() {
  1968. // If the available queue is empty, it is safe to reset MinReadyCycle.
  1969. if (Available.empty())
  1970. MinReadyCycle = std::numeric_limits<unsigned>::max();
  1971. // Check to see if any of the pending instructions are ready to issue. If
  1972. // so, add them to the available queue.
  1973. bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
  1974. for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
  1975. SUnit *SU = *(Pending.begin()+i);
  1976. unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
  1977. if (ReadyCycle < MinReadyCycle)
  1978. MinReadyCycle = ReadyCycle;
  1979. if (!IsBuffered && ReadyCycle > CurrCycle)
  1980. continue;
  1981. if (checkHazard(SU))
  1982. continue;
  1983. if (Available.size() >= ReadyListLimit)
  1984. break;
  1985. Available.push(SU);
  1986. Pending.remove(Pending.begin()+i);
  1987. --i; --e;
  1988. }
  1989. CheckPending = false;
  1990. }
  1991. /// Remove SU from the ready set for this boundary.
  1992. void SchedBoundary::removeReady(SUnit *SU) {
  1993. if (Available.isInQueue(SU))
  1994. Available.remove(Available.find(SU));
  1995. else {
  1996. assert(Pending.isInQueue(SU) && "bad ready count");
  1997. Pending.remove(Pending.find(SU));
  1998. }
  1999. }
  2000. /// If this queue only has one ready candidate, return it. As a side effect,
  2001. /// defer any nodes that now hit a hazard, and advance the cycle until at least
  2002. /// one node is ready. If multiple instructions are ready, return NULL.
  2003. SUnit *SchedBoundary::pickOnlyChoice() {
  2004. if (CheckPending)
  2005. releasePending();
  2006. if (CurrMOps > 0) {
  2007. // Defer any ready instrs that now have a hazard.
  2008. for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
  2009. if (checkHazard(*I)) {
  2010. Pending.push(*I);
  2011. I = Available.remove(I);
  2012. continue;
  2013. }
  2014. ++I;
  2015. }
  2016. }
  2017. for (unsigned i = 0; Available.empty(); ++i) {
  2018. // FIXME: Re-enable assert once PR20057 is resolved.
  2019. // assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
  2020. // "permanent hazard");
  2021. (void)i;
  2022. bumpCycle(CurrCycle + 1);
  2023. releasePending();
  2024. }
  2025. DEBUG(Pending.dump());
  2026. DEBUG(Available.dump());
  2027. if (Available.size() == 1)
  2028. return *Available.begin();
  2029. return nullptr;
  2030. }
  2031. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2032. // This is useful information to dump after bumpNode.
  2033. // Note that the Queue contents are more useful before pickNodeFromQueue.
  2034. LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() {
  2035. unsigned ResFactor;
  2036. unsigned ResCount;
  2037. if (ZoneCritResIdx) {
  2038. ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
  2039. ResCount = getResourceCount(ZoneCritResIdx);
  2040. } else {
  2041. ResFactor = SchedModel->getMicroOpFactor();
  2042. ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
  2043. }
  2044. unsigned LFactor = SchedModel->getLatencyFactor();
  2045. dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
  2046. << " Retired: " << RetiredMOps;
  2047. dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
  2048. dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
  2049. << ResCount / ResFactor << " "
  2050. << SchedModel->getResourceName(ZoneCritResIdx)
  2051. << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
  2052. << (IsResourceLimited ? " - Resource" : " - Latency")
  2053. << " limited.\n";
  2054. }
  2055. #endif
  2056. //===----------------------------------------------------------------------===//
  2057. // GenericScheduler - Generic implementation of MachineSchedStrategy.
  2058. //===----------------------------------------------------------------------===//
  2059. void GenericSchedulerBase::SchedCandidate::
  2060. initResourceDelta(const ScheduleDAGMI *DAG,
  2061. const TargetSchedModel *SchedModel) {
  2062. if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
  2063. return;
  2064. const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
  2065. for (TargetSchedModel::ProcResIter
  2066. PI = SchedModel->getWriteProcResBegin(SC),
  2067. PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
  2068. if (PI->ProcResourceIdx == Policy.ReduceResIdx)
  2069. ResDelta.CritResources += PI->Cycles;
  2070. if (PI->ProcResourceIdx == Policy.DemandResIdx)
  2071. ResDelta.DemandedResources += PI->Cycles;
  2072. }
  2073. }
  2074. /// Set the CandPolicy given a scheduling zone given the current resources and
  2075. /// latencies inside and outside the zone.
  2076. void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
  2077. SchedBoundary &CurrZone,
  2078. SchedBoundary *OtherZone) {
  2079. // Apply preemptive heuristics based on the total latency and resources
  2080. // inside and outside this zone. Potential stalls should be considered before
  2081. // following this policy.
  2082. // Compute remaining latency. We need this both to determine whether the
  2083. // overall schedule has become latency-limited and whether the instructions
  2084. // outside this zone are resource or latency limited.
  2085. //
  2086. // The "dependent" latency is updated incrementally during scheduling as the
  2087. // max height/depth of scheduled nodes minus the cycles since it was
  2088. // scheduled:
  2089. // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
  2090. //
  2091. // The "independent" latency is the max ready queue depth:
  2092. // ILat = max N.depth for N in Available|Pending
  2093. //
  2094. // RemainingLatency is the greater of independent and dependent latency.
  2095. unsigned RemLatency = CurrZone.getDependentLatency();
  2096. RemLatency = std::max(RemLatency,
  2097. CurrZone.findMaxLatency(CurrZone.Available.elements()));
  2098. RemLatency = std::max(RemLatency,
  2099. CurrZone.findMaxLatency(CurrZone.Pending.elements()));
  2100. // Compute the critical resource outside the zone.
  2101. unsigned OtherCritIdx = 0;
  2102. unsigned OtherCount =
  2103. OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
  2104. bool OtherResLimited = false;
  2105. if (SchedModel->hasInstrSchedModel()) {
  2106. unsigned LFactor = SchedModel->getLatencyFactor();
  2107. OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
  2108. }
  2109. // Schedule aggressively for latency in PostRA mode. We don't check for
  2110. // acyclic latency during PostRA, and highly out-of-order processors will
  2111. // skip PostRA scheduling.
  2112. if (!OtherResLimited) {
  2113. if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
  2114. Policy.ReduceLatency |= true;
  2115. DEBUG(dbgs() << " " << CurrZone.Available.getName()
  2116. << " RemainingLatency " << RemLatency << " + "
  2117. << CurrZone.getCurrCycle() << "c > CritPath "
  2118. << Rem.CriticalPath << "\n");
  2119. }
  2120. }
  2121. // If the same resource is limiting inside and outside the zone, do nothing.
  2122. if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
  2123. return;
  2124. DEBUG(
  2125. if (CurrZone.isResourceLimited()) {
  2126. dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
  2127. << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
  2128. << "\n";
  2129. }
  2130. if (OtherResLimited)
  2131. dbgs() << " RemainingLimit: "
  2132. << SchedModel->getResourceName(OtherCritIdx) << "\n";
  2133. if (!CurrZone.isResourceLimited() && !OtherResLimited)
  2134. dbgs() << " Latency limited both directions.\n");
  2135. if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
  2136. Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
  2137. if (OtherResLimited)
  2138. Policy.DemandResIdx = OtherCritIdx;
  2139. }
  2140. #ifndef NDEBUG
  2141. const char *GenericSchedulerBase::getReasonStr(
  2142. GenericSchedulerBase::CandReason Reason) {
  2143. switch (Reason) {
  2144. case NoCand: return "NOCAND ";
  2145. case Only1: return "ONLY1 ";
  2146. case PhysRegCopy: return "PREG-COPY ";
  2147. case RegExcess: return "REG-EXCESS";
  2148. case RegCritical: return "REG-CRIT ";
  2149. case Stall: return "STALL ";
  2150. case Cluster: return "CLUSTER ";
  2151. case Weak: return "WEAK ";
  2152. case RegMax: return "REG-MAX ";
  2153. case ResourceReduce: return "RES-REDUCE";
  2154. case ResourceDemand: return "RES-DEMAND";
  2155. case TopDepthReduce: return "TOP-DEPTH ";
  2156. case TopPathReduce: return "TOP-PATH ";
  2157. case BotHeightReduce:return "BOT-HEIGHT";
  2158. case BotPathReduce: return "BOT-PATH ";
  2159. case NextDefUse: return "DEF-USE ";
  2160. case NodeOrder: return "ORDER ";
  2161. };
  2162. llvm_unreachable("Unknown reason!");
  2163. }
  2164. void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
  2165. PressureChange P;
  2166. unsigned ResIdx = 0;
  2167. unsigned Latency = 0;
  2168. switch (Cand.Reason) {
  2169. default:
  2170. break;
  2171. case RegExcess:
  2172. P = Cand.RPDelta.Excess;
  2173. break;
  2174. case RegCritical:
  2175. P = Cand.RPDelta.CriticalMax;
  2176. break;
  2177. case RegMax:
  2178. P = Cand.RPDelta.CurrentMax;
  2179. break;
  2180. case ResourceReduce:
  2181. ResIdx = Cand.Policy.ReduceResIdx;
  2182. break;
  2183. case ResourceDemand:
  2184. ResIdx = Cand.Policy.DemandResIdx;
  2185. break;
  2186. case TopDepthReduce:
  2187. Latency = Cand.SU->getDepth();
  2188. break;
  2189. case TopPathReduce:
  2190. Latency = Cand.SU->getHeight();
  2191. break;
  2192. case BotHeightReduce:
  2193. Latency = Cand.SU->getHeight();
  2194. break;
  2195. case BotPathReduce:
  2196. Latency = Cand.SU->getDepth();
  2197. break;
  2198. }
  2199. dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
  2200. if (P.isValid())
  2201. dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
  2202. << ":" << P.getUnitInc() << " ";
  2203. else
  2204. dbgs() << " ";
  2205. if (ResIdx)
  2206. dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
  2207. else
  2208. dbgs() << " ";
  2209. if (Latency)
  2210. dbgs() << " " << Latency << " cycles ";
  2211. else
  2212. dbgs() << " ";
  2213. dbgs() << '\n';
  2214. }
  2215. #endif
  2216. /// Return true if this heuristic determines order.
  2217. static bool tryLess(int TryVal, int CandVal,
  2218. GenericSchedulerBase::SchedCandidate &TryCand,
  2219. GenericSchedulerBase::SchedCandidate &Cand,
  2220. GenericSchedulerBase::CandReason Reason) {
  2221. if (TryVal < CandVal) {
  2222. TryCand.Reason = Reason;
  2223. return true;
  2224. }
  2225. if (TryVal > CandVal) {
  2226. if (Cand.Reason > Reason)
  2227. Cand.Reason = Reason;
  2228. return true;
  2229. }
  2230. return false;
  2231. }
  2232. static bool tryGreater(int TryVal, int CandVal,
  2233. GenericSchedulerBase::SchedCandidate &TryCand,
  2234. GenericSchedulerBase::SchedCandidate &Cand,
  2235. GenericSchedulerBase::CandReason Reason) {
  2236. if (TryVal > CandVal) {
  2237. TryCand.Reason = Reason;
  2238. return true;
  2239. }
  2240. if (TryVal < CandVal) {
  2241. if (Cand.Reason > Reason)
  2242. Cand.Reason = Reason;
  2243. return true;
  2244. }
  2245. return false;
  2246. }
  2247. static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
  2248. GenericSchedulerBase::SchedCandidate &Cand,
  2249. SchedBoundary &Zone) {
  2250. if (Zone.isTop()) {
  2251. if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
  2252. if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
  2253. TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
  2254. return true;
  2255. }
  2256. if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
  2257. TryCand, Cand, GenericSchedulerBase::TopPathReduce))
  2258. return true;
  2259. } else {
  2260. if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
  2261. if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
  2262. TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
  2263. return true;
  2264. }
  2265. if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
  2266. TryCand, Cand, GenericSchedulerBase::BotPathReduce))
  2267. return true;
  2268. }
  2269. return false;
  2270. }
  2271. static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
  2272. DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
  2273. << GenericSchedulerBase::getReasonStr(Reason) << '\n');
  2274. }
  2275. static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
  2276. tracePick(Cand.Reason, Cand.AtTop);
  2277. }
  2278. void GenericScheduler::initialize(ScheduleDAGMI *dag) {
  2279. assert(dag->hasVRegLiveness() &&
  2280. "(PreRA)GenericScheduler needs vreg liveness");
  2281. DAG = static_cast<ScheduleDAGMILive*>(dag);
  2282. SchedModel = DAG->getSchedModel();
  2283. TRI = DAG->TRI;
  2284. Rem.init(DAG, SchedModel);
  2285. Top.init(DAG, SchedModel, &Rem);
  2286. Bot.init(DAG, SchedModel, &Rem);
  2287. // Initialize resource counts.
  2288. // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
  2289. // are disabled, then these HazardRecs will be disabled.
  2290. const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
  2291. if (!Top.HazardRec) {
  2292. Top.HazardRec =
  2293. DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
  2294. Itin, DAG);
  2295. }
  2296. if (!Bot.HazardRec) {
  2297. Bot.HazardRec =
  2298. DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
  2299. Itin, DAG);
  2300. }
  2301. TopCand.SU = nullptr;
  2302. BotCand.SU = nullptr;
  2303. }
  2304. /// Initialize the per-region scheduling policy.
  2305. void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
  2306. MachineBasicBlock::iterator End,
  2307. unsigned NumRegionInstrs) {
  2308. const MachineFunction &MF = *Begin->getParent()->getParent();
  2309. const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
  2310. // Avoid setting up the register pressure tracker for small regions to save
  2311. // compile time. As a rough heuristic, only track pressure when the number of
  2312. // schedulable instructions exceeds half the integer register file.
  2313. RegionPolicy.ShouldTrackPressure = true;
  2314. for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
  2315. MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
  2316. if (TLI->isTypeLegal(LegalIntVT)) {
  2317. unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
  2318. TLI->getRegClassFor(LegalIntVT));
  2319. RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
  2320. }
  2321. }
  2322. // For generic targets, we default to bottom-up, because it's simpler and more
  2323. // compile-time optimizations have been implemented in that direction.
  2324. RegionPolicy.OnlyBottomUp = true;
  2325. // Allow the subtarget to override default policy.
  2326. MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
  2327. // After subtarget overrides, apply command line options.
  2328. if (!EnableRegPressure)
  2329. RegionPolicy.ShouldTrackPressure = false;
  2330. // Check -misched-topdown/bottomup can force or unforce scheduling direction.
  2331. // e.g. -misched-bottomup=false allows scheduling in both directions.
  2332. assert((!ForceTopDown || !ForceBottomUp) &&
  2333. "-misched-topdown incompatible with -misched-bottomup");
  2334. if (ForceBottomUp.getNumOccurrences() > 0) {
  2335. RegionPolicy.OnlyBottomUp = ForceBottomUp;
  2336. if (RegionPolicy.OnlyBottomUp)
  2337. RegionPolicy.OnlyTopDown = false;
  2338. }
  2339. if (ForceTopDown.getNumOccurrences() > 0) {
  2340. RegionPolicy.OnlyTopDown = ForceTopDown;
  2341. if (RegionPolicy.OnlyTopDown)
  2342. RegionPolicy.OnlyBottomUp = false;
  2343. }
  2344. }
  2345. void GenericScheduler::dumpPolicy() {
  2346. // Cannot completely remove virtual function even in release mode.
  2347. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2348. dbgs() << "GenericScheduler RegionPolicy: "
  2349. << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
  2350. << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
  2351. << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
  2352. << "\n";
  2353. #endif
  2354. }
  2355. /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
  2356. /// critical path by more cycles than it takes to drain the instruction buffer.
  2357. /// We estimate an upper bounds on in-flight instructions as:
  2358. ///
  2359. /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
  2360. /// InFlightIterations = AcyclicPath / CyclesPerIteration
  2361. /// InFlightResources = InFlightIterations * LoopResources
  2362. ///
  2363. /// TODO: Check execution resources in addition to IssueCount.
  2364. void GenericScheduler::checkAcyclicLatency() {
  2365. if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
  2366. return;
  2367. // Scaled number of cycles per loop iteration.
  2368. unsigned IterCount =
  2369. std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
  2370. Rem.RemIssueCount);
  2371. // Scaled acyclic critical path.
  2372. unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
  2373. // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
  2374. unsigned InFlightCount =
  2375. (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
  2376. unsigned BufferLimit =
  2377. SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
  2378. Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
  2379. DEBUG(dbgs() << "IssueCycles="
  2380. << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
  2381. << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
  2382. << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
  2383. << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
  2384. << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
  2385. if (Rem.IsAcyclicLatencyLimited)
  2386. dbgs() << " ACYCLIC LATENCY LIMIT\n");
  2387. }
  2388. void GenericScheduler::registerRoots() {
  2389. Rem.CriticalPath = DAG->ExitSU.getDepth();
  2390. // Some roots may not feed into ExitSU. Check all of them in case.
  2391. for (std::vector<SUnit*>::const_iterator
  2392. I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
  2393. if ((*I)->getDepth() > Rem.CriticalPath)
  2394. Rem.CriticalPath = (*I)->getDepth();
  2395. }
  2396. DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
  2397. if (DumpCriticalPathLength) {
  2398. errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
  2399. }
  2400. if (EnableCyclicPath) {
  2401. Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
  2402. checkAcyclicLatency();
  2403. }
  2404. }
  2405. static bool tryPressure(const PressureChange &TryP,
  2406. const PressureChange &CandP,
  2407. GenericSchedulerBase::SchedCandidate &TryCand,
  2408. GenericSchedulerBase::SchedCandidate &Cand,
  2409. GenericSchedulerBase::CandReason Reason,
  2410. const TargetRegisterInfo *TRI,
  2411. const MachineFunction &MF) {
  2412. // If one candidate decreases and the other increases, go with it.
  2413. // Invalid candidates have UnitInc==0.
  2414. if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
  2415. Reason)) {
  2416. return true;
  2417. }
  2418. // Do not compare the magnitude of pressure changes between top and bottom
  2419. // boundary.
  2420. if (Cand.AtTop != TryCand.AtTop)
  2421. return false;
  2422. // If both candidates affect the same set in the same boundary, go with the
  2423. // smallest increase.
  2424. unsigned TryPSet = TryP.getPSetOrMax();
  2425. unsigned CandPSet = CandP.getPSetOrMax();
  2426. if (TryPSet == CandPSet) {
  2427. return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
  2428. Reason);
  2429. }
  2430. int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
  2431. std::numeric_limits<int>::max();
  2432. int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
  2433. std::numeric_limits<int>::max();
  2434. // If the candidates are decreasing pressure, reverse priority.
  2435. if (TryP.getUnitInc() < 0)
  2436. std::swap(TryRank, CandRank);
  2437. return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
  2438. }
  2439. static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
  2440. return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
  2441. }
  2442. /// Minimize physical register live ranges. Regalloc wants them adjacent to
  2443. /// their physreg def/use.
  2444. ///
  2445. /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
  2446. /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
  2447. /// with the operation that produces or consumes the physreg. We'll do this when
  2448. /// regalloc has support for parallel copies.
  2449. static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
  2450. const MachineInstr *MI = SU->getInstr();
  2451. if (!MI->isCopy())
  2452. return 0;
  2453. unsigned ScheduledOper = isTop ? 1 : 0;
  2454. unsigned UnscheduledOper = isTop ? 0 : 1;
  2455. // If we have already scheduled the physreg produce/consumer, immediately
  2456. // schedule the copy.
  2457. if (TargetRegisterInfo::isPhysicalRegister(
  2458. MI->getOperand(ScheduledOper).getReg()))
  2459. return 1;
  2460. // If the physreg is at the boundary, defer it. Otherwise schedule it
  2461. // immediately to free the dependent. We can hoist the copy later.
  2462. bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
  2463. if (TargetRegisterInfo::isPhysicalRegister(
  2464. MI->getOperand(UnscheduledOper).getReg()))
  2465. return AtBoundary ? -1 : 1;
  2466. return 0;
  2467. }
  2468. void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
  2469. bool AtTop,
  2470. const RegPressureTracker &RPTracker,
  2471. RegPressureTracker &TempTracker) {
  2472. Cand.SU = SU;
  2473. Cand.AtTop = AtTop;
  2474. if (DAG->isTrackingPressure()) {
  2475. if (AtTop) {
  2476. TempTracker.getMaxDownwardPressureDelta(
  2477. Cand.SU->getInstr(),
  2478. Cand.RPDelta,
  2479. DAG->getRegionCriticalPSets(),
  2480. DAG->getRegPressure().MaxSetPressure);
  2481. } else {
  2482. if (VerifyScheduling) {
  2483. TempTracker.getMaxUpwardPressureDelta(
  2484. Cand.SU->getInstr(),
  2485. &DAG->getPressureDiff(Cand.SU),
  2486. Cand.RPDelta,
  2487. DAG->getRegionCriticalPSets(),
  2488. DAG->getRegPressure().MaxSetPressure);
  2489. } else {
  2490. RPTracker.getUpwardPressureDelta(
  2491. Cand.SU->getInstr(),
  2492. DAG->getPressureDiff(Cand.SU),
  2493. Cand.RPDelta,
  2494. DAG->getRegionCriticalPSets(),
  2495. DAG->getRegPressure().MaxSetPressure);
  2496. }
  2497. }
  2498. }
  2499. DEBUG(if (Cand.RPDelta.Excess.isValid())
  2500. dbgs() << " Try SU(" << Cand.SU->NodeNum << ") "
  2501. << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet())
  2502. << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n");
  2503. }
  2504. /// Apply a set of heursitics to a new candidate. Heuristics are currently
  2505. /// hierarchical. This may be more efficient than a graduated cost model because
  2506. /// we don't need to evaluate all aspects of the model for each node in the
  2507. /// queue. But it's really done to make the heuristics easier to debug and
  2508. /// statistically analyze.
  2509. ///
  2510. /// \param Cand provides the policy and current best candidate.
  2511. /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
  2512. /// \param Zone describes the scheduled zone that we are extending, or nullptr
  2513. // if Cand is from a different zone than TryCand.
  2514. void GenericScheduler::tryCandidate(SchedCandidate &Cand,
  2515. SchedCandidate &TryCand,
  2516. SchedBoundary *Zone) {
  2517. // Initialize the candidate if needed.
  2518. if (!Cand.isValid()) {
  2519. TryCand.Reason = NodeOrder;
  2520. return;
  2521. }
  2522. if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
  2523. biasPhysRegCopy(Cand.SU, Cand.AtTop),
  2524. TryCand, Cand, PhysRegCopy))
  2525. return;
  2526. // Avoid exceeding the target's limit.
  2527. if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
  2528. Cand.RPDelta.Excess,
  2529. TryCand, Cand, RegExcess, TRI,
  2530. DAG->MF))
  2531. return;
  2532. // Avoid increasing the max critical pressure in the scheduled region.
  2533. if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
  2534. Cand.RPDelta.CriticalMax,
  2535. TryCand, Cand, RegCritical, TRI,
  2536. DAG->MF))
  2537. return;
  2538. // We only compare a subset of features when comparing nodes between
  2539. // Top and Bottom boundary. Some properties are simply incomparable, in many
  2540. // other instances we should only override the other boundary if something
  2541. // is a clear good pick on one boundary. Skip heuristics that are more
  2542. // "tie-breaking" in nature.
  2543. bool SameBoundary = Zone != nullptr;
  2544. if (SameBoundary) {
  2545. // For loops that are acyclic path limited, aggressively schedule for
  2546. // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
  2547. // heuristics to take precedence.
  2548. if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
  2549. tryLatency(TryCand, Cand, *Zone))
  2550. return;
  2551. // Prioritize instructions that read unbuffered resources by stall cycles.
  2552. if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
  2553. Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
  2554. return;
  2555. }
  2556. // Keep clustered nodes together to encourage downstream peephole
  2557. // optimizations which may reduce resource requirements.
  2558. //
  2559. // This is a best effort to set things up for a post-RA pass. Optimizations
  2560. // like generating loads of multiple registers should ideally be done within
  2561. // the scheduler pass by combining the loads during DAG postprocessing.
  2562. const SUnit *CandNextClusterSU =
  2563. Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
  2564. const SUnit *TryCandNextClusterSU =
  2565. TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
  2566. if (tryGreater(TryCand.SU == TryCandNextClusterSU,
  2567. Cand.SU == CandNextClusterSU,
  2568. TryCand, Cand, Cluster))
  2569. return;
  2570. if (SameBoundary) {
  2571. // Weak edges are for clustering and other constraints.
  2572. if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
  2573. getWeakLeft(Cand.SU, Cand.AtTop),
  2574. TryCand, Cand, Weak))
  2575. return;
  2576. }
  2577. // Avoid increasing the max pressure of the entire region.
  2578. if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
  2579. Cand.RPDelta.CurrentMax,
  2580. TryCand, Cand, RegMax, TRI,
  2581. DAG->MF))
  2582. return;
  2583. if (SameBoundary) {
  2584. // Avoid critical resource consumption and balance the schedule.
  2585. TryCand.initResourceDelta(DAG, SchedModel);
  2586. if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
  2587. TryCand, Cand, ResourceReduce))
  2588. return;
  2589. if (tryGreater(TryCand.ResDelta.DemandedResources,
  2590. Cand.ResDelta.DemandedResources,
  2591. TryCand, Cand, ResourceDemand))
  2592. return;
  2593. // Avoid serializing long latency dependence chains.
  2594. // For acyclic path limited loops, latency was already checked above.
  2595. if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
  2596. !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
  2597. return;
  2598. // Fall through to original instruction order.
  2599. if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
  2600. || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
  2601. TryCand.Reason = NodeOrder;
  2602. }
  2603. }
  2604. }
  2605. /// Pick the best candidate from the queue.
  2606. ///
  2607. /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
  2608. /// DAG building. To adjust for the current scheduling location we need to
  2609. /// maintain the number of vreg uses remaining to be top-scheduled.
  2610. void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
  2611. const CandPolicy &ZonePolicy,
  2612. const RegPressureTracker &RPTracker,
  2613. SchedCandidate &Cand) {
  2614. // getMaxPressureDelta temporarily modifies the tracker.
  2615. RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
  2616. ReadyQueue &Q = Zone.Available;
  2617. for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
  2618. SchedCandidate TryCand(ZonePolicy);
  2619. initCandidate(TryCand, *I, Zone.isTop(), RPTracker, TempTracker);
  2620. // Pass SchedBoundary only when comparing nodes from the same boundary.
  2621. SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
  2622. tryCandidate(Cand, TryCand, ZoneArg);
  2623. if (TryCand.Reason != NoCand) {
  2624. // Initialize resource delta if needed in case future heuristics query it.
  2625. if (TryCand.ResDelta == SchedResourceDelta())
  2626. TryCand.initResourceDelta(DAG, SchedModel);
  2627. Cand.setBest(TryCand);
  2628. DEBUG(traceCandidate(Cand));
  2629. }
  2630. }
  2631. }
  2632. /// Pick the best candidate node from either the top or bottom queue.
  2633. SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
  2634. // Schedule as far as possible in the direction of no choice. This is most
  2635. // efficient, but also provides the best heuristics for CriticalPSets.
  2636. if (SUnit *SU = Bot.pickOnlyChoice()) {
  2637. IsTopNode = false;
  2638. tracePick(Only1, false);
  2639. return SU;
  2640. }
  2641. if (SUnit *SU = Top.pickOnlyChoice()) {
  2642. IsTopNode = true;
  2643. tracePick(Only1, true);
  2644. return SU;
  2645. }
  2646. // Set the bottom-up policy based on the state of the current bottom zone and
  2647. // the instructions outside the zone, including the top zone.
  2648. CandPolicy BotPolicy;
  2649. setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
  2650. // Set the top-down policy based on the state of the current top zone and
  2651. // the instructions outside the zone, including the bottom zone.
  2652. CandPolicy TopPolicy;
  2653. setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
  2654. // See if BotCand is still valid (because we previously scheduled from Top).
  2655. DEBUG(dbgs() << "Picking from Bot:\n");
  2656. if (!BotCand.isValid() || BotCand.SU->isScheduled ||
  2657. BotCand.Policy != BotPolicy) {
  2658. BotCand.reset(CandPolicy());
  2659. pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
  2660. assert(BotCand.Reason != NoCand && "failed to find the first candidate");
  2661. } else {
  2662. DEBUG(traceCandidate(BotCand));
  2663. #ifndef NDEBUG
  2664. if (VerifyScheduling) {
  2665. SchedCandidate TCand;
  2666. TCand.reset(CandPolicy());
  2667. pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
  2668. assert(TCand.SU == BotCand.SU &&
  2669. "Last pick result should correspond to re-picking right now");
  2670. }
  2671. #endif
  2672. }
  2673. // Check if the top Q has a better candidate.
  2674. DEBUG(dbgs() << "Picking from Top:\n");
  2675. if (!TopCand.isValid() || TopCand.SU->isScheduled ||
  2676. TopCand.Policy != TopPolicy) {
  2677. TopCand.reset(CandPolicy());
  2678. pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
  2679. assert(TopCand.Reason != NoCand && "failed to find the first candidate");
  2680. } else {
  2681. DEBUG(traceCandidate(TopCand));
  2682. #ifndef NDEBUG
  2683. if (VerifyScheduling) {
  2684. SchedCandidate TCand;
  2685. TCand.reset(CandPolicy());
  2686. pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
  2687. assert(TCand.SU == TopCand.SU &&
  2688. "Last pick result should correspond to re-picking right now");
  2689. }
  2690. #endif
  2691. }
  2692. // Pick best from BotCand and TopCand.
  2693. assert(BotCand.isValid());
  2694. assert(TopCand.isValid());
  2695. SchedCandidate Cand = BotCand;
  2696. TopCand.Reason = NoCand;
  2697. tryCandidate(Cand, TopCand, nullptr);
  2698. if (TopCand.Reason != NoCand) {
  2699. Cand.setBest(TopCand);
  2700. DEBUG(traceCandidate(Cand));
  2701. }
  2702. IsTopNode = Cand.AtTop;
  2703. tracePick(Cand);
  2704. return Cand.SU;
  2705. }
  2706. /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
  2707. SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
  2708. if (DAG->top() == DAG->bottom()) {
  2709. assert(Top.Available.empty() && Top.Pending.empty() &&
  2710. Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
  2711. return nullptr;
  2712. }
  2713. SUnit *SU;
  2714. do {
  2715. if (RegionPolicy.OnlyTopDown) {
  2716. SU = Top.pickOnlyChoice();
  2717. if (!SU) {
  2718. CandPolicy NoPolicy;
  2719. TopCand.reset(NoPolicy);
  2720. pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
  2721. assert(TopCand.Reason != NoCand && "failed to find a candidate");
  2722. tracePick(TopCand);
  2723. SU = TopCand.SU;
  2724. }
  2725. IsTopNode = true;
  2726. } else if (RegionPolicy.OnlyBottomUp) {
  2727. SU = Bot.pickOnlyChoice();
  2728. if (!SU) {
  2729. CandPolicy NoPolicy;
  2730. BotCand.reset(NoPolicy);
  2731. pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
  2732. assert(BotCand.Reason != NoCand && "failed to find a candidate");
  2733. tracePick(BotCand);
  2734. SU = BotCand.SU;
  2735. }
  2736. IsTopNode = false;
  2737. } else {
  2738. SU = pickNodeBidirectional(IsTopNode);
  2739. }
  2740. } while (SU->isScheduled);
  2741. if (SU->isTopReady())
  2742. Top.removeReady(SU);
  2743. if (SU->isBottomReady())
  2744. Bot.removeReady(SU);
  2745. DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
  2746. return SU;
  2747. }
  2748. void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
  2749. MachineBasicBlock::iterator InsertPos = SU->getInstr();
  2750. if (!isTop)
  2751. ++InsertPos;
  2752. SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
  2753. // Find already scheduled copies with a single physreg dependence and move
  2754. // them just above the scheduled instruction.
  2755. for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
  2756. I != E; ++I) {
  2757. if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
  2758. continue;
  2759. SUnit *DepSU = I->getSUnit();
  2760. if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
  2761. continue;
  2762. MachineInstr *Copy = DepSU->getInstr();
  2763. if (!Copy->isCopy())
  2764. continue;
  2765. DEBUG(dbgs() << " Rescheduling physreg copy ";
  2766. I->getSUnit()->dump(DAG));
  2767. DAG->moveInstruction(Copy, InsertPos);
  2768. }
  2769. }
  2770. /// Update the scheduler's state after scheduling a node. This is the same node
  2771. /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
  2772. /// update it's state based on the current cycle before MachineSchedStrategy
  2773. /// does.
  2774. ///
  2775. /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
  2776. /// them here. See comments in biasPhysRegCopy.
  2777. void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
  2778. if (IsTopNode) {
  2779. SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
  2780. Top.bumpNode(SU);
  2781. if (SU->hasPhysRegUses)
  2782. reschedulePhysRegCopies(SU, true);
  2783. } else {
  2784. SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
  2785. Bot.bumpNode(SU);
  2786. if (SU->hasPhysRegDefs)
  2787. reschedulePhysRegCopies(SU, false);
  2788. }
  2789. }
  2790. /// Create the standard converging machine scheduler. This will be used as the
  2791. /// default scheduler if the target does not set a default.
  2792. ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
  2793. ScheduleDAGMILive *DAG =
  2794. new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
  2795. // Register DAG post-processors.
  2796. //
  2797. // FIXME: extend the mutation API to allow earlier mutations to instantiate
  2798. // data and pass it to later mutations. Have a single mutation that gathers
  2799. // the interesting nodes in one pass.
  2800. DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
  2801. return DAG;
  2802. }
  2803. static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
  2804. return createGenericSchedLive(C);
  2805. }
  2806. static MachineSchedRegistry
  2807. GenericSchedRegistry("converge", "Standard converging scheduler.",
  2808. createConveringSched);
  2809. //===----------------------------------------------------------------------===//
  2810. // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
  2811. //===----------------------------------------------------------------------===//
  2812. void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
  2813. DAG = Dag;
  2814. SchedModel = DAG->getSchedModel();
  2815. TRI = DAG->TRI;
  2816. Rem.init(DAG, SchedModel);
  2817. Top.init(DAG, SchedModel, &Rem);
  2818. BotRoots.clear();
  2819. // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
  2820. // or are disabled, then these HazardRecs will be disabled.
  2821. const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
  2822. if (!Top.HazardRec) {
  2823. Top.HazardRec =
  2824. DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
  2825. Itin, DAG);
  2826. }
  2827. }
  2828. void PostGenericScheduler::registerRoots() {
  2829. Rem.CriticalPath = DAG->ExitSU.getDepth();
  2830. // Some roots may not feed into ExitSU. Check all of them in case.
  2831. for (SmallVectorImpl<SUnit*>::const_iterator
  2832. I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
  2833. if ((*I)->getDepth() > Rem.CriticalPath)
  2834. Rem.CriticalPath = (*I)->getDepth();
  2835. }
  2836. DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
  2837. if (DumpCriticalPathLength) {
  2838. errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
  2839. }
  2840. }
  2841. /// Apply a set of heursitics to a new candidate for PostRA scheduling.
  2842. ///
  2843. /// \param Cand provides the policy and current best candidate.
  2844. /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
  2845. void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
  2846. SchedCandidate &TryCand) {
  2847. // Initialize the candidate if needed.
  2848. if (!Cand.isValid()) {
  2849. TryCand.Reason = NodeOrder;
  2850. return;
  2851. }
  2852. // Prioritize instructions that read unbuffered resources by stall cycles.
  2853. if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
  2854. Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
  2855. return;
  2856. // Avoid critical resource consumption and balance the schedule.
  2857. if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
  2858. TryCand, Cand, ResourceReduce))
  2859. return;
  2860. if (tryGreater(TryCand.ResDelta.DemandedResources,
  2861. Cand.ResDelta.DemandedResources,
  2862. TryCand, Cand, ResourceDemand))
  2863. return;
  2864. // Avoid serializing long latency dependence chains.
  2865. if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
  2866. return;
  2867. }
  2868. // Fall through to original instruction order.
  2869. if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
  2870. TryCand.Reason = NodeOrder;
  2871. }
  2872. void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
  2873. ReadyQueue &Q = Top.Available;
  2874. for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
  2875. SchedCandidate TryCand(Cand.Policy);
  2876. TryCand.SU = *I;
  2877. TryCand.AtTop = true;
  2878. TryCand.initResourceDelta(DAG, SchedModel);
  2879. tryCandidate(Cand, TryCand);
  2880. if (TryCand.Reason != NoCand) {
  2881. Cand.setBest(TryCand);
  2882. DEBUG(traceCandidate(Cand));
  2883. }
  2884. }
  2885. }
  2886. /// Pick the next node to schedule.
  2887. SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
  2888. if (DAG->top() == DAG->bottom()) {
  2889. assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
  2890. return nullptr;
  2891. }
  2892. SUnit *SU;
  2893. do {
  2894. SU = Top.pickOnlyChoice();
  2895. if (SU) {
  2896. tracePick(Only1, true);
  2897. } else {
  2898. CandPolicy NoPolicy;
  2899. SchedCandidate TopCand(NoPolicy);
  2900. // Set the top-down policy based on the state of the current top zone and
  2901. // the instructions outside the zone, including the bottom zone.
  2902. setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
  2903. pickNodeFromQueue(TopCand);
  2904. assert(TopCand.Reason != NoCand && "failed to find a candidate");
  2905. tracePick(TopCand);
  2906. SU = TopCand.SU;
  2907. }
  2908. } while (SU->isScheduled);
  2909. IsTopNode = true;
  2910. Top.removeReady(SU);
  2911. DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
  2912. return SU;
  2913. }
  2914. /// Called after ScheduleDAGMI has scheduled an instruction and updated
  2915. /// scheduled/remaining flags in the DAG nodes.
  2916. void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
  2917. SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
  2918. Top.bumpNode(SU);
  2919. }
  2920. ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
  2921. return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
  2922. /*RemoveKillFlags=*/true);
  2923. }
  2924. //===----------------------------------------------------------------------===//
  2925. // ILP Scheduler. Currently for experimental analysis of heuristics.
  2926. //===----------------------------------------------------------------------===//
  2927. namespace {
  2928. /// \brief Order nodes by the ILP metric.
  2929. struct ILPOrder {
  2930. const SchedDFSResult *DFSResult = nullptr;
  2931. const BitVector *ScheduledTrees = nullptr;
  2932. bool MaximizeILP;
  2933. ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
  2934. /// \brief Apply a less-than relation on node priority.
  2935. ///
  2936. /// (Return true if A comes after B in the Q.)
  2937. bool operator()(const SUnit *A, const SUnit *B) const {
  2938. unsigned SchedTreeA = DFSResult->getSubtreeID(A);
  2939. unsigned SchedTreeB = DFSResult->getSubtreeID(B);
  2940. if (SchedTreeA != SchedTreeB) {
  2941. // Unscheduled trees have lower priority.
  2942. if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
  2943. return ScheduledTrees->test(SchedTreeB);
  2944. // Trees with shallower connections have have lower priority.
  2945. if (DFSResult->getSubtreeLevel(SchedTreeA)
  2946. != DFSResult->getSubtreeLevel(SchedTreeB)) {
  2947. return DFSResult->getSubtreeLevel(SchedTreeA)
  2948. < DFSResult->getSubtreeLevel(SchedTreeB);
  2949. }
  2950. }
  2951. if (MaximizeILP)
  2952. return DFSResult->getILP(A) < DFSResult->getILP(B);
  2953. else
  2954. return DFSResult->getILP(A) > DFSResult->getILP(B);
  2955. }
  2956. };
  2957. /// \brief Schedule based on the ILP metric.
  2958. class ILPScheduler : public MachineSchedStrategy {
  2959. ScheduleDAGMILive *DAG = nullptr;
  2960. ILPOrder Cmp;
  2961. std::vector<SUnit*> ReadyQ;
  2962. public:
  2963. ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
  2964. void initialize(ScheduleDAGMI *dag) override {
  2965. assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
  2966. DAG = static_cast<ScheduleDAGMILive*>(dag);
  2967. DAG->computeDFSResult();
  2968. Cmp.DFSResult = DAG->getDFSResult();
  2969. Cmp.ScheduledTrees = &DAG->getScheduledTrees();
  2970. ReadyQ.clear();
  2971. }
  2972. void registerRoots() override {
  2973. // Restore the heap in ReadyQ with the updated DFS results.
  2974. std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  2975. }
  2976. /// Implement MachineSchedStrategy interface.
  2977. /// -----------------------------------------
  2978. /// Callback to select the highest priority node from the ready Q.
  2979. SUnit *pickNode(bool &IsTopNode) override {
  2980. if (ReadyQ.empty()) return nullptr;
  2981. std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  2982. SUnit *SU = ReadyQ.back();
  2983. ReadyQ.pop_back();
  2984. IsTopNode = false;
  2985. DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
  2986. << " ILP: " << DAG->getDFSResult()->getILP(SU)
  2987. << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
  2988. << DAG->getDFSResult()->getSubtreeLevel(
  2989. DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
  2990. << "Scheduling " << *SU->getInstr());
  2991. return SU;
  2992. }
  2993. /// \brief Scheduler callback to notify that a new subtree is scheduled.
  2994. void scheduleTree(unsigned SubtreeID) override {
  2995. std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  2996. }
  2997. /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
  2998. /// DFSResults, and resort the priority Q.
  2999. void schedNode(SUnit *SU, bool IsTopNode) override {
  3000. assert(!IsTopNode && "SchedDFSResult needs bottom-up");
  3001. }
  3002. void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
  3003. void releaseBottomNode(SUnit *SU) override {
  3004. ReadyQ.push_back(SU);
  3005. std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
  3006. }
  3007. };
  3008. } // end anonymous namespace
  3009. static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
  3010. return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
  3011. }
  3012. static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
  3013. return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
  3014. }
  3015. static MachineSchedRegistry ILPMaxRegistry(
  3016. "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
  3017. static MachineSchedRegistry ILPMinRegistry(
  3018. "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
  3019. //===----------------------------------------------------------------------===//
  3020. // Machine Instruction Shuffler for Correctness Testing
  3021. //===----------------------------------------------------------------------===//
  3022. #ifndef NDEBUG
  3023. namespace {
  3024. /// Apply a less-than relation on the node order, which corresponds to the
  3025. /// instruction order prior to scheduling. IsReverse implements greater-than.
  3026. template<bool IsReverse>
  3027. struct SUnitOrder {
  3028. bool operator()(SUnit *A, SUnit *B) const {
  3029. if (IsReverse)
  3030. return A->NodeNum > B->NodeNum;
  3031. else
  3032. return A->NodeNum < B->NodeNum;
  3033. }
  3034. };
  3035. /// Reorder instructions as much as possible.
  3036. class InstructionShuffler : public MachineSchedStrategy {
  3037. bool IsAlternating;
  3038. bool IsTopDown;
  3039. // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
  3040. // gives nodes with a higher number higher priority causing the latest
  3041. // instructions to be scheduled first.
  3042. PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
  3043. TopQ;
  3044. // When scheduling bottom-up, use greater-than as the queue priority.
  3045. PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
  3046. BottomQ;
  3047. public:
  3048. InstructionShuffler(bool alternate, bool topdown)
  3049. : IsAlternating(alternate), IsTopDown(topdown) {}
  3050. void initialize(ScheduleDAGMI*) override {
  3051. TopQ.clear();
  3052. BottomQ.clear();
  3053. }
  3054. /// Implement MachineSchedStrategy interface.
  3055. /// -----------------------------------------
  3056. SUnit *pickNode(bool &IsTopNode) override {
  3057. SUnit *SU;
  3058. if (IsTopDown) {
  3059. do {
  3060. if (TopQ.empty()) return nullptr;
  3061. SU = TopQ.top();
  3062. TopQ.pop();
  3063. } while (SU->isScheduled);
  3064. IsTopNode = true;
  3065. } else {
  3066. do {
  3067. if (BottomQ.empty()) return nullptr;
  3068. SU = BottomQ.top();
  3069. BottomQ.pop();
  3070. } while (SU->isScheduled);
  3071. IsTopNode = false;
  3072. }
  3073. if (IsAlternating)
  3074. IsTopDown = !IsTopDown;
  3075. return SU;
  3076. }
  3077. void schedNode(SUnit *SU, bool IsTopNode) override {}
  3078. void releaseTopNode(SUnit *SU) override {
  3079. TopQ.push(SU);
  3080. }
  3081. void releaseBottomNode(SUnit *SU) override {
  3082. BottomQ.push(SU);
  3083. }
  3084. };
  3085. } // end anonymous namespace
  3086. static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
  3087. bool Alternate = !ForceTopDown && !ForceBottomUp;
  3088. bool TopDown = !ForceBottomUp;
  3089. assert((TopDown || !ForceTopDown) &&
  3090. "-misched-topdown incompatible with -misched-bottomup");
  3091. return new ScheduleDAGMILive(
  3092. C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
  3093. }
  3094. static MachineSchedRegistry ShufflerRegistry(
  3095. "shuffle", "Shuffle machine instructions alternating directions",
  3096. createInstructionShuffler);
  3097. #endif // !NDEBUG
  3098. //===----------------------------------------------------------------------===//
  3099. // GraphWriter support for ScheduleDAGMILive.
  3100. //===----------------------------------------------------------------------===//
  3101. #ifndef NDEBUG
  3102. namespace llvm {
  3103. template<> struct GraphTraits<
  3104. ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
  3105. template<>
  3106. struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
  3107. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  3108. static std::string getGraphName(const ScheduleDAG *G) {
  3109. return G->MF.getName();
  3110. }
  3111. static bool renderGraphFromBottomUp() {
  3112. return true;
  3113. }
  3114. static bool isNodeHidden(const SUnit *Node) {
  3115. if (ViewMISchedCutoff == 0)
  3116. return false;
  3117. return (Node->Preds.size() > ViewMISchedCutoff
  3118. || Node->Succs.size() > ViewMISchedCutoff);
  3119. }
  3120. /// If you want to override the dot attributes printed for a particular
  3121. /// edge, override this method.
  3122. static std::string getEdgeAttributes(const SUnit *Node,
  3123. SUnitIterator EI,
  3124. const ScheduleDAG *Graph) {
  3125. if (EI.isArtificialDep())
  3126. return "color=cyan,style=dashed";
  3127. if (EI.isCtrlDep())
  3128. return "color=blue,style=dashed";
  3129. return "";
  3130. }
  3131. static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
  3132. std::string Str;
  3133. raw_string_ostream SS(Str);
  3134. const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
  3135. const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
  3136. static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
  3137. SS << "SU:" << SU->NodeNum;
  3138. if (DFS)
  3139. SS << " I:" << DFS->getNumInstrs(SU);
  3140. return SS.str();
  3141. }
  3142. static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
  3143. return G->getGraphNodeLabel(SU);
  3144. }
  3145. static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
  3146. std::string Str("shape=Mrecord");
  3147. const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
  3148. const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
  3149. static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
  3150. if (DFS) {
  3151. Str += ",style=filled,fillcolor=\"#";
  3152. Str += DOT::getColorString(DFS->getSubtreeID(N));
  3153. Str += '"';
  3154. }
  3155. return Str;
  3156. }
  3157. };
  3158. } // end namespace llvm
  3159. #endif // NDEBUG
  3160. /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
  3161. /// rendered using 'dot'.
  3162. ///
  3163. void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
  3164. #ifndef NDEBUG
  3165. ViewGraph(this, Name, false, Title);
  3166. #else
  3167. errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
  3168. << "systems with Graphviz or gv!\n";
  3169. #endif // NDEBUG
  3170. }
  3171. /// Out-of-line implementation with no arguments is handy for gdb.
  3172. void ScheduleDAGMI::viewGraph() {
  3173. viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
  3174. }