MachineScheduler.cpp 129 KB

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