MachineScheduler.cpp 124 KB

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