MachineScheduler.cpp 124 KB

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