MachineScheduler.cpp 126 KB

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