MachineScheduler.cpp 110 KB

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