MachineScheduler.cpp 132 KB

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