MachineScheduler.cpp 107 KB

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