MachineScheduler.cpp 120 KB

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