MachineScheduler.cpp 133 KB

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