MachineScheduler.cpp 145 KB

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