ScheduleDAGRRList.cpp 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210
  1. //===- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements bottom-up and top-down register pressure reduction list
  10. // schedulers, using standard algorithms. The basic approach uses a priority
  11. // queue of available nodes to schedule. One at a time, nodes are taken from
  12. // the priority queue (thus in priority order), checked for legality to
  13. // schedule, and emitted if legal.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "ScheduleDAGSDNodes.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/CodeGen/ISDOpcodes.h"
  24. #include "llvm/CodeGen/MachineFunction.h"
  25. #include "llvm/CodeGen/MachineOperand.h"
  26. #include "llvm/CodeGen/Register.h"
  27. #include "llvm/CodeGen/ScheduleDAG.h"
  28. #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
  29. #include "llvm/CodeGen/SchedulerRegistry.h"
  30. #include "llvm/CodeGen/SelectionDAGISel.h"
  31. #include "llvm/CodeGen/SelectionDAGNodes.h"
  32. #include "llvm/CodeGen/TargetInstrInfo.h"
  33. #include "llvm/CodeGen/TargetLowering.h"
  34. #include "llvm/CodeGen/TargetOpcodes.h"
  35. #include "llvm/CodeGen/TargetRegisterInfo.h"
  36. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  37. #include "llvm/Config/llvm-config.h"
  38. #include "llvm/IR/InlineAsm.h"
  39. #include "llvm/MC/MCInstrDesc.h"
  40. #include "llvm/MC/MCRegisterInfo.h"
  41. #include "llvm/Support/Casting.h"
  42. #include "llvm/Support/CodeGen.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/Compiler.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include "llvm/Support/MachineValueType.h"
  48. #include "llvm/Support/raw_ostream.h"
  49. #include <algorithm>
  50. #include <cassert>
  51. #include <cstdint>
  52. #include <cstdlib>
  53. #include <iterator>
  54. #include <limits>
  55. #include <memory>
  56. #include <utility>
  57. #include <vector>
  58. using namespace llvm;
  59. #define DEBUG_TYPE "pre-RA-sched"
  60. STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
  61. STATISTIC(NumUnfolds, "Number of nodes unfolded");
  62. STATISTIC(NumDups, "Number of duplicated nodes");
  63. STATISTIC(NumPRCopies, "Number of physical register copies");
  64. static RegisterScheduler
  65. burrListDAGScheduler("list-burr",
  66. "Bottom-up register reduction list scheduling",
  67. createBURRListDAGScheduler);
  68. static RegisterScheduler
  69. sourceListDAGScheduler("source",
  70. "Similar to list-burr but schedules in source "
  71. "order when possible",
  72. createSourceListDAGScheduler);
  73. static RegisterScheduler
  74. hybridListDAGScheduler("list-hybrid",
  75. "Bottom-up register pressure aware list scheduling "
  76. "which tries to balance latency and register pressure",
  77. createHybridListDAGScheduler);
  78. static RegisterScheduler
  79. ILPListDAGScheduler("list-ilp",
  80. "Bottom-up register pressure aware list scheduling "
  81. "which tries to balance ILP and register pressure",
  82. createILPListDAGScheduler);
  83. static cl::opt<bool> DisableSchedCycles(
  84. "disable-sched-cycles", cl::Hidden, cl::init(false),
  85. cl::desc("Disable cycle-level precision during preRA scheduling"));
  86. // Temporary sched=list-ilp flags until the heuristics are robust.
  87. // Some options are also available under sched=list-hybrid.
  88. static cl::opt<bool> DisableSchedRegPressure(
  89. "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
  90. cl::desc("Disable regpressure priority in sched=list-ilp"));
  91. static cl::opt<bool> DisableSchedLiveUses(
  92. "disable-sched-live-uses", cl::Hidden, cl::init(true),
  93. cl::desc("Disable live use priority in sched=list-ilp"));
  94. static cl::opt<bool> DisableSchedVRegCycle(
  95. "disable-sched-vrcycle", cl::Hidden, cl::init(false),
  96. cl::desc("Disable virtual register cycle interference checks"));
  97. static cl::opt<bool> DisableSchedPhysRegJoin(
  98. "disable-sched-physreg-join", cl::Hidden, cl::init(false),
  99. cl::desc("Disable physreg def-use affinity"));
  100. static cl::opt<bool> DisableSchedStalls(
  101. "disable-sched-stalls", cl::Hidden, cl::init(true),
  102. cl::desc("Disable no-stall priority in sched=list-ilp"));
  103. static cl::opt<bool> DisableSchedCriticalPath(
  104. "disable-sched-critical-path", cl::Hidden, cl::init(false),
  105. cl::desc("Disable critical path priority in sched=list-ilp"));
  106. static cl::opt<bool> DisableSchedHeight(
  107. "disable-sched-height", cl::Hidden, cl::init(false),
  108. cl::desc("Disable scheduled-height priority in sched=list-ilp"));
  109. static cl::opt<bool> Disable2AddrHack(
  110. "disable-2addr-hack", cl::Hidden, cl::init(true),
  111. cl::desc("Disable scheduler's two-address hack"));
  112. static cl::opt<int> MaxReorderWindow(
  113. "max-sched-reorder", cl::Hidden, cl::init(6),
  114. cl::desc("Number of instructions to allow ahead of the critical path "
  115. "in sched=list-ilp"));
  116. static cl::opt<unsigned> AvgIPC(
  117. "sched-avg-ipc", cl::Hidden, cl::init(1),
  118. cl::desc("Average inst/cycle whan no target itinerary exists."));
  119. namespace {
  120. //===----------------------------------------------------------------------===//
  121. /// ScheduleDAGRRList - The actual register reduction list scheduler
  122. /// implementation. This supports both top-down and bottom-up scheduling.
  123. ///
  124. class ScheduleDAGRRList : public ScheduleDAGSDNodes {
  125. private:
  126. /// NeedLatency - True if the scheduler will make use of latency information.
  127. bool NeedLatency;
  128. /// AvailableQueue - The priority queue to use for the available SUnits.
  129. SchedulingPriorityQueue *AvailableQueue;
  130. /// PendingQueue - This contains all of the instructions whose operands have
  131. /// been issued, but their results are not ready yet (due to the latency of
  132. /// the operation). Once the operands becomes available, the instruction is
  133. /// added to the AvailableQueue.
  134. std::vector<SUnit *> PendingQueue;
  135. /// HazardRec - The hazard recognizer to use.
  136. ScheduleHazardRecognizer *HazardRec;
  137. /// CurCycle - The current scheduler state corresponds to this cycle.
  138. unsigned CurCycle = 0;
  139. /// MinAvailableCycle - Cycle of the soonest available instruction.
  140. unsigned MinAvailableCycle;
  141. /// IssueCount - Count instructions issued in this cycle
  142. /// Currently valid only for bottom-up scheduling.
  143. unsigned IssueCount;
  144. /// LiveRegDefs - A set of physical registers and their definition
  145. /// that are "live". These nodes must be scheduled before any other nodes that
  146. /// modifies the registers can be scheduled.
  147. unsigned NumLiveRegs;
  148. std::unique_ptr<SUnit*[]> LiveRegDefs;
  149. std::unique_ptr<SUnit*[]> LiveRegGens;
  150. // Collect interferences between physical register use/defs.
  151. // Each interference is an SUnit and set of physical registers.
  152. SmallVector<SUnit*, 4> Interferences;
  153. using LRegsMapT = DenseMap<SUnit *, SmallVector<unsigned, 4>>;
  154. LRegsMapT LRegsMap;
  155. /// Topo - A topological ordering for SUnits which permits fast IsReachable
  156. /// and similar queries.
  157. ScheduleDAGTopologicalSort Topo;
  158. // Hack to keep track of the inverse of FindCallSeqStart without more crazy
  159. // DAG crawling.
  160. DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
  161. public:
  162. ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
  163. SchedulingPriorityQueue *availqueue,
  164. CodeGenOpt::Level OptLevel)
  165. : ScheduleDAGSDNodes(mf),
  166. NeedLatency(needlatency), AvailableQueue(availqueue),
  167. Topo(SUnits, nullptr) {
  168. const TargetSubtargetInfo &STI = mf.getSubtarget();
  169. if (DisableSchedCycles || !NeedLatency)
  170. HazardRec = new ScheduleHazardRecognizer();
  171. else
  172. HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this);
  173. }
  174. ~ScheduleDAGRRList() override {
  175. delete HazardRec;
  176. delete AvailableQueue;
  177. }
  178. void Schedule() override;
  179. ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
  180. /// IsReachable - Checks if SU is reachable from TargetSU.
  181. bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
  182. return Topo.IsReachable(SU, TargetSU);
  183. }
  184. /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
  185. /// create a cycle.
  186. bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
  187. return Topo.WillCreateCycle(SU, TargetSU);
  188. }
  189. /// AddPredQueued - Queues and update to add a predecessor edge to SUnit SU.
  190. /// This returns true if this is a new predecessor.
  191. /// Does *NOT* update the topological ordering! It just queues an update.
  192. void AddPredQueued(SUnit *SU, const SDep &D) {
  193. Topo.AddPredQueued(SU, D.getSUnit());
  194. SU->addPred(D);
  195. }
  196. /// AddPred - adds a predecessor edge to SUnit SU.
  197. /// This returns true if this is a new predecessor.
  198. /// Updates the topological ordering if required.
  199. void AddPred(SUnit *SU, const SDep &D) {
  200. Topo.AddPred(SU, D.getSUnit());
  201. SU->addPred(D);
  202. }
  203. /// RemovePred - removes a predecessor edge from SUnit SU.
  204. /// This returns true if an edge was removed.
  205. /// Updates the topological ordering if required.
  206. void RemovePred(SUnit *SU, const SDep &D) {
  207. Topo.RemovePred(SU, D.getSUnit());
  208. SU->removePred(D);
  209. }
  210. private:
  211. bool isReady(SUnit *SU) {
  212. return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
  213. AvailableQueue->isReady(SU);
  214. }
  215. void ReleasePred(SUnit *SU, const SDep *PredEdge);
  216. void ReleasePredecessors(SUnit *SU);
  217. void ReleasePending();
  218. void AdvanceToCycle(unsigned NextCycle);
  219. void AdvancePastStalls(SUnit *SU);
  220. void EmitNode(SUnit *SU);
  221. void ScheduleNodeBottomUp(SUnit*);
  222. void CapturePred(SDep *PredEdge);
  223. void UnscheduleNodeBottomUp(SUnit*);
  224. void RestoreHazardCheckerBottomUp();
  225. void BacktrackBottomUp(SUnit*, SUnit*);
  226. SUnit *TryUnfoldSU(SUnit *);
  227. SUnit *CopyAndMoveSuccessors(SUnit*);
  228. void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
  229. const TargetRegisterClass*,
  230. const TargetRegisterClass*,
  231. SmallVectorImpl<SUnit*>&);
  232. bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
  233. void releaseInterferences(unsigned Reg = 0);
  234. SUnit *PickNodeToScheduleBottomUp();
  235. void ListScheduleBottomUp();
  236. /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
  237. SUnit *CreateNewSUnit(SDNode *N) {
  238. unsigned NumSUnits = SUnits.size();
  239. SUnit *NewNode = newSUnit(N);
  240. // Update the topological ordering.
  241. if (NewNode->NodeNum >= NumSUnits)
  242. Topo.AddSUnitWithoutPredecessors(NewNode);
  243. return NewNode;
  244. }
  245. /// CreateClone - Creates a new SUnit from an existing one.
  246. SUnit *CreateClone(SUnit *N) {
  247. unsigned NumSUnits = SUnits.size();
  248. SUnit *NewNode = Clone(N);
  249. // Update the topological ordering.
  250. if (NewNode->NodeNum >= NumSUnits)
  251. Topo.AddSUnitWithoutPredecessors(NewNode);
  252. return NewNode;
  253. }
  254. /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
  255. /// need actual latency information but the hybrid scheduler does.
  256. bool forceUnitLatencies() const override {
  257. return !NeedLatency;
  258. }
  259. };
  260. } // end anonymous namespace
  261. static constexpr unsigned RegSequenceCost = 1;
  262. /// GetCostForDef - Looks up the register class and cost for a given definition.
  263. /// Typically this just means looking up the representative register class,
  264. /// but for untyped values (MVT::Untyped) it means inspecting the node's
  265. /// opcode to determine what register class is being generated.
  266. static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
  267. const TargetLowering *TLI,
  268. const TargetInstrInfo *TII,
  269. const TargetRegisterInfo *TRI,
  270. unsigned &RegClass, unsigned &Cost,
  271. const MachineFunction &MF) {
  272. MVT VT = RegDefPos.GetValue();
  273. // Special handling for untyped values. These values can only come from
  274. // the expansion of custom DAG-to-DAG patterns.
  275. if (VT == MVT::Untyped) {
  276. const SDNode *Node = RegDefPos.GetNode();
  277. // Special handling for CopyFromReg of untyped values.
  278. if (!Node->isMachineOpcode() && Node->getOpcode() == ISD::CopyFromReg) {
  279. Register Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
  280. const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg);
  281. RegClass = RC->getID();
  282. Cost = 1;
  283. return;
  284. }
  285. unsigned Opcode = Node->getMachineOpcode();
  286. if (Opcode == TargetOpcode::REG_SEQUENCE) {
  287. unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
  288. const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
  289. RegClass = RC->getID();
  290. Cost = RegSequenceCost;
  291. return;
  292. }
  293. unsigned Idx = RegDefPos.GetIdx();
  294. const MCInstrDesc &Desc = TII->get(Opcode);
  295. const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF);
  296. assert(RC && "Not a valid register class");
  297. RegClass = RC->getID();
  298. // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
  299. // better way to determine it.
  300. Cost = 1;
  301. } else {
  302. RegClass = TLI->getRepRegClassFor(VT)->getID();
  303. Cost = TLI->getRepRegClassCostFor(VT);
  304. }
  305. }
  306. /// Schedule - Schedule the DAG using list scheduling.
  307. void ScheduleDAGRRList::Schedule() {
  308. LLVM_DEBUG(dbgs() << "********** List Scheduling " << printMBBReference(*BB)
  309. << " '" << BB->getName() << "' **********\n");
  310. CurCycle = 0;
  311. IssueCount = 0;
  312. MinAvailableCycle =
  313. DisableSchedCycles ? 0 : std::numeric_limits<unsigned>::max();
  314. NumLiveRegs = 0;
  315. // Allocate slots for each physical register, plus one for a special register
  316. // to track the virtual resource of a calling sequence.
  317. LiveRegDefs.reset(new SUnit*[TRI->getNumRegs() + 1]());
  318. LiveRegGens.reset(new SUnit*[TRI->getNumRegs() + 1]());
  319. CallSeqEndForStart.clear();
  320. assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
  321. // Build the scheduling graph.
  322. BuildSchedGraph(nullptr);
  323. LLVM_DEBUG(dump());
  324. Topo.MarkDirty();
  325. AvailableQueue->initNodes(SUnits);
  326. HazardRec->Reset();
  327. // Execute the actual scheduling loop.
  328. ListScheduleBottomUp();
  329. AvailableQueue->releaseState();
  330. LLVM_DEBUG({
  331. dbgs() << "*** Final schedule ***\n";
  332. dumpSchedule();
  333. dbgs() << '\n';
  334. });
  335. }
  336. //===----------------------------------------------------------------------===//
  337. // Bottom-Up Scheduling
  338. //===----------------------------------------------------------------------===//
  339. /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
  340. /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
  341. void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
  342. SUnit *PredSU = PredEdge->getSUnit();
  343. #ifndef NDEBUG
  344. if (PredSU->NumSuccsLeft == 0) {
  345. dbgs() << "*** Scheduling failed! ***\n";
  346. dumpNode(*PredSU);
  347. dbgs() << " has been released too many times!\n";
  348. llvm_unreachable(nullptr);
  349. }
  350. #endif
  351. --PredSU->NumSuccsLeft;
  352. if (!forceUnitLatencies()) {
  353. // Updating predecessor's height. This is now the cycle when the
  354. // predecessor can be scheduled without causing a pipeline stall.
  355. PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
  356. }
  357. // If all the node's successors are scheduled, this node is ready
  358. // to be scheduled. Ignore the special EntrySU node.
  359. if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
  360. PredSU->isAvailable = true;
  361. unsigned Height = PredSU->getHeight();
  362. if (Height < MinAvailableCycle)
  363. MinAvailableCycle = Height;
  364. if (isReady(PredSU)) {
  365. AvailableQueue->push(PredSU);
  366. }
  367. // CapturePred and others may have left the node in the pending queue, avoid
  368. // adding it twice.
  369. else if (!PredSU->isPending) {
  370. PredSU->isPending = true;
  371. PendingQueue.push_back(PredSU);
  372. }
  373. }
  374. }
  375. /// IsChainDependent - Test if Outer is reachable from Inner through
  376. /// chain dependencies.
  377. static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
  378. unsigned NestLevel,
  379. const TargetInstrInfo *TII) {
  380. SDNode *N = Outer;
  381. while (true) {
  382. if (N == Inner)
  383. return true;
  384. // For a TokenFactor, examine each operand. There may be multiple ways
  385. // to get to the CALLSEQ_BEGIN, but we need to find the path with the
  386. // most nesting in order to ensure that we find the corresponding match.
  387. if (N->getOpcode() == ISD::TokenFactor) {
  388. for (const SDValue &Op : N->op_values())
  389. if (IsChainDependent(Op.getNode(), Inner, NestLevel, TII))
  390. return true;
  391. return false;
  392. }
  393. // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
  394. if (N->isMachineOpcode()) {
  395. if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  396. ++NestLevel;
  397. } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
  398. if (NestLevel == 0)
  399. return false;
  400. --NestLevel;
  401. }
  402. }
  403. // Otherwise, find the chain and continue climbing.
  404. for (const SDValue &Op : N->op_values())
  405. if (Op.getValueType() == MVT::Other) {
  406. N = Op.getNode();
  407. goto found_chain_operand;
  408. }
  409. return false;
  410. found_chain_operand:;
  411. if (N->getOpcode() == ISD::EntryToken)
  412. return false;
  413. }
  414. }
  415. /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
  416. /// the corresponding (lowered) CALLSEQ_BEGIN node.
  417. ///
  418. /// NestLevel and MaxNested are used in recursion to indcate the current level
  419. /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
  420. /// level seen so far.
  421. ///
  422. /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
  423. /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
  424. static SDNode *
  425. FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
  426. const TargetInstrInfo *TII) {
  427. while (true) {
  428. // For a TokenFactor, examine each operand. There may be multiple ways
  429. // to get to the CALLSEQ_BEGIN, but we need to find the path with the
  430. // most nesting in order to ensure that we find the corresponding match.
  431. if (N->getOpcode() == ISD::TokenFactor) {
  432. SDNode *Best = nullptr;
  433. unsigned BestMaxNest = MaxNest;
  434. for (const SDValue &Op : N->op_values()) {
  435. unsigned MyNestLevel = NestLevel;
  436. unsigned MyMaxNest = MaxNest;
  437. if (SDNode *New = FindCallSeqStart(Op.getNode(),
  438. MyNestLevel, MyMaxNest, TII))
  439. if (!Best || (MyMaxNest > BestMaxNest)) {
  440. Best = New;
  441. BestMaxNest = MyMaxNest;
  442. }
  443. }
  444. assert(Best);
  445. MaxNest = BestMaxNest;
  446. return Best;
  447. }
  448. // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
  449. if (N->isMachineOpcode()) {
  450. if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  451. ++NestLevel;
  452. MaxNest = std::max(MaxNest, NestLevel);
  453. } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
  454. assert(NestLevel != 0);
  455. --NestLevel;
  456. if (NestLevel == 0)
  457. return N;
  458. }
  459. }
  460. // Otherwise, find the chain and continue climbing.
  461. for (const SDValue &Op : N->op_values())
  462. if (Op.getValueType() == MVT::Other) {
  463. N = Op.getNode();
  464. goto found_chain_operand;
  465. }
  466. return nullptr;
  467. found_chain_operand:;
  468. if (N->getOpcode() == ISD::EntryToken)
  469. return nullptr;
  470. }
  471. }
  472. /// Call ReleasePred for each predecessor, then update register live def/gen.
  473. /// Always update LiveRegDefs for a register dependence even if the current SU
  474. /// also defines the register. This effectively create one large live range
  475. /// across a sequence of two-address node. This is important because the
  476. /// entire chain must be scheduled together. Example:
  477. ///
  478. /// flags = (3) add
  479. /// flags = (2) addc flags
  480. /// flags = (1) addc flags
  481. ///
  482. /// results in
  483. ///
  484. /// LiveRegDefs[flags] = 3
  485. /// LiveRegGens[flags] = 1
  486. ///
  487. /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
  488. /// interference on flags.
  489. void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
  490. // Bottom up: release predecessors
  491. for (SDep &Pred : SU->Preds) {
  492. ReleasePred(SU, &Pred);
  493. if (Pred.isAssignedRegDep()) {
  494. // This is a physical register dependency and it's impossible or
  495. // expensive to copy the register. Make sure nothing that can
  496. // clobber the register is scheduled between the predecessor and
  497. // this node.
  498. SUnit *RegDef = LiveRegDefs[Pred.getReg()]; (void)RegDef;
  499. assert((!RegDef || RegDef == SU || RegDef == Pred.getSUnit()) &&
  500. "interference on register dependence");
  501. LiveRegDefs[Pred.getReg()] = Pred.getSUnit();
  502. if (!LiveRegGens[Pred.getReg()]) {
  503. ++NumLiveRegs;
  504. LiveRegGens[Pred.getReg()] = SU;
  505. }
  506. }
  507. }
  508. // If we're scheduling a lowered CALLSEQ_END, find the corresponding
  509. // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
  510. // these nodes, to prevent other calls from being interscheduled with them.
  511. unsigned CallResource = TRI->getNumRegs();
  512. if (!LiveRegDefs[CallResource])
  513. for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
  514. if (Node->isMachineOpcode() &&
  515. Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  516. unsigned NestLevel = 0;
  517. unsigned MaxNest = 0;
  518. SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
  519. assert(N && "Must find call sequence start");
  520. SUnit *Def = &SUnits[N->getNodeId()];
  521. CallSeqEndForStart[Def] = SU;
  522. ++NumLiveRegs;
  523. LiveRegDefs[CallResource] = Def;
  524. LiveRegGens[CallResource] = SU;
  525. break;
  526. }
  527. }
  528. /// Check to see if any of the pending instructions are ready to issue. If
  529. /// so, add them to the available queue.
  530. void ScheduleDAGRRList::ReleasePending() {
  531. if (DisableSchedCycles) {
  532. assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
  533. return;
  534. }
  535. // If the available queue is empty, it is safe to reset MinAvailableCycle.
  536. if (AvailableQueue->empty())
  537. MinAvailableCycle = std::numeric_limits<unsigned>::max();
  538. // Check to see if any of the pending instructions are ready to issue. If
  539. // so, add them to the available queue.
  540. for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
  541. unsigned ReadyCycle = PendingQueue[i]->getHeight();
  542. if (ReadyCycle < MinAvailableCycle)
  543. MinAvailableCycle = ReadyCycle;
  544. if (PendingQueue[i]->isAvailable) {
  545. if (!isReady(PendingQueue[i]))
  546. continue;
  547. AvailableQueue->push(PendingQueue[i]);
  548. }
  549. PendingQueue[i]->isPending = false;
  550. PendingQueue[i] = PendingQueue.back();
  551. PendingQueue.pop_back();
  552. --i; --e;
  553. }
  554. }
  555. /// Move the scheduler state forward by the specified number of Cycles.
  556. void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
  557. if (NextCycle <= CurCycle)
  558. return;
  559. IssueCount = 0;
  560. AvailableQueue->setCurCycle(NextCycle);
  561. if (!HazardRec->isEnabled()) {
  562. // Bypass lots of virtual calls in case of long latency.
  563. CurCycle = NextCycle;
  564. }
  565. else {
  566. for (; CurCycle != NextCycle; ++CurCycle) {
  567. HazardRec->RecedeCycle();
  568. }
  569. }
  570. // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
  571. // available Q to release pending nodes at least once before popping.
  572. ReleasePending();
  573. }
  574. /// Move the scheduler state forward until the specified node's dependents are
  575. /// ready and can be scheduled with no resource conflicts.
  576. void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
  577. if (DisableSchedCycles)
  578. return;
  579. // FIXME: Nodes such as CopyFromReg probably should not advance the current
  580. // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
  581. // has predecessors the cycle will be advanced when they are scheduled.
  582. // But given the crude nature of modeling latency though such nodes, we
  583. // currently need to treat these nodes like real instructions.
  584. // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
  585. unsigned ReadyCycle = SU->getHeight();
  586. // Bump CurCycle to account for latency. We assume the latency of other
  587. // available instructions may be hidden by the stall (not a full pipe stall).
  588. // This updates the hazard recognizer's cycle before reserving resources for
  589. // this instruction.
  590. AdvanceToCycle(ReadyCycle);
  591. // Calls are scheduled in their preceding cycle, so don't conflict with
  592. // hazards from instructions after the call. EmitNode will reset the
  593. // scoreboard state before emitting the call.
  594. if (SU->isCall)
  595. return;
  596. // FIXME: For resource conflicts in very long non-pipelined stages, we
  597. // should probably skip ahead here to avoid useless scoreboard checks.
  598. int Stalls = 0;
  599. while (true) {
  600. ScheduleHazardRecognizer::HazardType HT =
  601. HazardRec->getHazardType(SU, -Stalls);
  602. if (HT == ScheduleHazardRecognizer::NoHazard)
  603. break;
  604. ++Stalls;
  605. }
  606. AdvanceToCycle(CurCycle + Stalls);
  607. }
  608. /// Record this SUnit in the HazardRecognizer.
  609. /// Does not update CurCycle.
  610. void ScheduleDAGRRList::EmitNode(SUnit *SU) {
  611. if (!HazardRec->isEnabled())
  612. return;
  613. // Check for phys reg copy.
  614. if (!SU->getNode())
  615. return;
  616. switch (SU->getNode()->getOpcode()) {
  617. default:
  618. assert(SU->getNode()->isMachineOpcode() &&
  619. "This target-independent node should not be scheduled.");
  620. break;
  621. case ISD::MERGE_VALUES:
  622. case ISD::TokenFactor:
  623. case ISD::LIFETIME_START:
  624. case ISD::LIFETIME_END:
  625. case ISD::CopyToReg:
  626. case ISD::CopyFromReg:
  627. case ISD::EH_LABEL:
  628. // Noops don't affect the scoreboard state. Copies are likely to be
  629. // removed.
  630. return;
  631. case ISD::INLINEASM:
  632. case ISD::INLINEASM_BR:
  633. // For inline asm, clear the pipeline state.
  634. HazardRec->Reset();
  635. return;
  636. }
  637. if (SU->isCall) {
  638. // Calls are scheduled with their preceding instructions. For bottom-up
  639. // scheduling, clear the pipeline state before emitting.
  640. HazardRec->Reset();
  641. }
  642. HazardRec->EmitInstruction(SU);
  643. }
  644. static void resetVRegCycle(SUnit *SU);
  645. /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
  646. /// count of its predecessors. If a predecessor pending count is zero, add it to
  647. /// the Available queue.
  648. void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
  649. LLVM_DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
  650. LLVM_DEBUG(dumpNode(*SU));
  651. #ifndef NDEBUG
  652. if (CurCycle < SU->getHeight())
  653. LLVM_DEBUG(dbgs() << " Height [" << SU->getHeight()
  654. << "] pipeline stall!\n");
  655. #endif
  656. // FIXME: Do not modify node height. It may interfere with
  657. // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
  658. // node its ready cycle can aid heuristics, and after scheduling it can
  659. // indicate the scheduled cycle.
  660. SU->setHeightToAtLeast(CurCycle);
  661. // Reserve resources for the scheduled instruction.
  662. EmitNode(SU);
  663. Sequence.push_back(SU);
  664. AvailableQueue->scheduledNode(SU);
  665. // If HazardRec is disabled, and each inst counts as one cycle, then
  666. // advance CurCycle before ReleasePredecessors to avoid useless pushes to
  667. // PendingQueue for schedulers that implement HasReadyFilter.
  668. if (!HazardRec->isEnabled() && AvgIPC < 2)
  669. AdvanceToCycle(CurCycle + 1);
  670. // Update liveness of predecessors before successors to avoid treating a
  671. // two-address node as a live range def.
  672. ReleasePredecessors(SU);
  673. // Release all the implicit physical register defs that are live.
  674. for (SDep &Succ : SU->Succs) {
  675. // LiveRegDegs[Succ.getReg()] != SU when SU is a two-address node.
  676. if (Succ.isAssignedRegDep() && LiveRegDefs[Succ.getReg()] == SU) {
  677. assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
  678. --NumLiveRegs;
  679. LiveRegDefs[Succ.getReg()] = nullptr;
  680. LiveRegGens[Succ.getReg()] = nullptr;
  681. releaseInterferences(Succ.getReg());
  682. }
  683. }
  684. // Release the special call resource dependence, if this is the beginning
  685. // of a call.
  686. unsigned CallResource = TRI->getNumRegs();
  687. if (LiveRegDefs[CallResource] == SU)
  688. for (const SDNode *SUNode = SU->getNode(); SUNode;
  689. SUNode = SUNode->getGluedNode()) {
  690. if (SUNode->isMachineOpcode() &&
  691. SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
  692. assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
  693. --NumLiveRegs;
  694. LiveRegDefs[CallResource] = nullptr;
  695. LiveRegGens[CallResource] = nullptr;
  696. releaseInterferences(CallResource);
  697. }
  698. }
  699. resetVRegCycle(SU);
  700. SU->isScheduled = true;
  701. // Conditions under which the scheduler should eagerly advance the cycle:
  702. // (1) No available instructions
  703. // (2) All pipelines full, so available instructions must have hazards.
  704. //
  705. // If HazardRec is disabled, the cycle was pre-advanced before calling
  706. // ReleasePredecessors. In that case, IssueCount should remain 0.
  707. //
  708. // Check AvailableQueue after ReleasePredecessors in case of zero latency.
  709. if (HazardRec->isEnabled() || AvgIPC > 1) {
  710. if (SU->getNode() && SU->getNode()->isMachineOpcode())
  711. ++IssueCount;
  712. if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
  713. || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
  714. AdvanceToCycle(CurCycle + 1);
  715. }
  716. }
  717. /// CapturePred - This does the opposite of ReleasePred. Since SU is being
  718. /// unscheduled, increase the succ left count of its predecessors. Remove
  719. /// them from AvailableQueue if necessary.
  720. void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
  721. SUnit *PredSU = PredEdge->getSUnit();
  722. if (PredSU->isAvailable) {
  723. PredSU->isAvailable = false;
  724. if (!PredSU->isPending)
  725. AvailableQueue->remove(PredSU);
  726. }
  727. assert(PredSU->NumSuccsLeft < std::numeric_limits<unsigned>::max() &&
  728. "NumSuccsLeft will overflow!");
  729. ++PredSU->NumSuccsLeft;
  730. }
  731. /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
  732. /// its predecessor states to reflect the change.
  733. void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
  734. LLVM_DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
  735. LLVM_DEBUG(dumpNode(*SU));
  736. for (SDep &Pred : SU->Preds) {
  737. CapturePred(&Pred);
  738. if (Pred.isAssignedRegDep() && SU == LiveRegGens[Pred.getReg()]){
  739. assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
  740. assert(LiveRegDefs[Pred.getReg()] == Pred.getSUnit() &&
  741. "Physical register dependency violated?");
  742. --NumLiveRegs;
  743. LiveRegDefs[Pred.getReg()] = nullptr;
  744. LiveRegGens[Pred.getReg()] = nullptr;
  745. releaseInterferences(Pred.getReg());
  746. }
  747. }
  748. // Reclaim the special call resource dependence, if this is the beginning
  749. // of a call.
  750. unsigned CallResource = TRI->getNumRegs();
  751. for (const SDNode *SUNode = SU->getNode(); SUNode;
  752. SUNode = SUNode->getGluedNode()) {
  753. if (SUNode->isMachineOpcode() &&
  754. SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
  755. SUnit *SeqEnd = CallSeqEndForStart[SU];
  756. assert(SeqEnd && "Call sequence start/end must be known");
  757. assert(!LiveRegDefs[CallResource]);
  758. assert(!LiveRegGens[CallResource]);
  759. ++NumLiveRegs;
  760. LiveRegDefs[CallResource] = SU;
  761. LiveRegGens[CallResource] = SeqEnd;
  762. }
  763. }
  764. // Release the special call resource dependence, if this is the end
  765. // of a call.
  766. if (LiveRegGens[CallResource] == SU)
  767. for (const SDNode *SUNode = SU->getNode(); SUNode;
  768. SUNode = SUNode->getGluedNode()) {
  769. if (SUNode->isMachineOpcode() &&
  770. SUNode->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  771. assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
  772. assert(LiveRegDefs[CallResource]);
  773. assert(LiveRegGens[CallResource]);
  774. --NumLiveRegs;
  775. LiveRegDefs[CallResource] = nullptr;
  776. LiveRegGens[CallResource] = nullptr;
  777. releaseInterferences(CallResource);
  778. }
  779. }
  780. for (auto &Succ : SU->Succs) {
  781. if (Succ.isAssignedRegDep()) {
  782. auto Reg = Succ.getReg();
  783. if (!LiveRegDefs[Reg])
  784. ++NumLiveRegs;
  785. // This becomes the nearest def. Note that an earlier def may still be
  786. // pending if this is a two-address node.
  787. LiveRegDefs[Reg] = SU;
  788. // Update LiveRegGen only if was empty before this unscheduling.
  789. // This is to avoid incorrect updating LiveRegGen set in previous run.
  790. if (!LiveRegGens[Reg]) {
  791. // Find the successor with the lowest height.
  792. LiveRegGens[Reg] = Succ.getSUnit();
  793. for (auto &Succ2 : SU->Succs) {
  794. if (Succ2.isAssignedRegDep() && Succ2.getReg() == Reg &&
  795. Succ2.getSUnit()->getHeight() < LiveRegGens[Reg]->getHeight())
  796. LiveRegGens[Reg] = Succ2.getSUnit();
  797. }
  798. }
  799. }
  800. }
  801. if (SU->getHeight() < MinAvailableCycle)
  802. MinAvailableCycle = SU->getHeight();
  803. SU->setHeightDirty();
  804. SU->isScheduled = false;
  805. SU->isAvailable = true;
  806. if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
  807. // Don't make available until backtracking is complete.
  808. SU->isPending = true;
  809. PendingQueue.push_back(SU);
  810. }
  811. else {
  812. AvailableQueue->push(SU);
  813. }
  814. AvailableQueue->unscheduledNode(SU);
  815. }
  816. /// After backtracking, the hazard checker needs to be restored to a state
  817. /// corresponding the current cycle.
  818. void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
  819. HazardRec->Reset();
  820. unsigned LookAhead = std::min((unsigned)Sequence.size(),
  821. HazardRec->getMaxLookAhead());
  822. if (LookAhead == 0)
  823. return;
  824. std::vector<SUnit *>::const_iterator I = (Sequence.end() - LookAhead);
  825. unsigned HazardCycle = (*I)->getHeight();
  826. for (auto E = Sequence.end(); I != E; ++I) {
  827. SUnit *SU = *I;
  828. for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
  829. HazardRec->RecedeCycle();
  830. }
  831. EmitNode(SU);
  832. }
  833. }
  834. /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
  835. /// BTCycle in order to schedule a specific node.
  836. void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
  837. SUnit *OldSU = Sequence.back();
  838. while (true) {
  839. Sequence.pop_back();
  840. // FIXME: use ready cycle instead of height
  841. CurCycle = OldSU->getHeight();
  842. UnscheduleNodeBottomUp(OldSU);
  843. AvailableQueue->setCurCycle(CurCycle);
  844. if (OldSU == BtSU)
  845. break;
  846. OldSU = Sequence.back();
  847. }
  848. assert(!SU->isSucc(OldSU) && "Something is wrong!");
  849. RestoreHazardCheckerBottomUp();
  850. ReleasePending();
  851. ++NumBacktracks;
  852. }
  853. static bool isOperandOf(const SUnit *SU, SDNode *N) {
  854. for (const SDNode *SUNode = SU->getNode(); SUNode;
  855. SUNode = SUNode->getGluedNode()) {
  856. if (SUNode->isOperandOf(N))
  857. return true;
  858. }
  859. return false;
  860. }
  861. /// TryUnfold - Attempt to unfold
  862. SUnit *ScheduleDAGRRList::TryUnfoldSU(SUnit *SU) {
  863. SDNode *N = SU->getNode();
  864. // Use while over if to ease fall through.
  865. SmallVector<SDNode *, 2> NewNodes;
  866. if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
  867. return nullptr;
  868. // unfolding an x86 DEC64m operation results in store, dec, load which
  869. // can't be handled here so quit
  870. if (NewNodes.size() == 3)
  871. return nullptr;
  872. assert(NewNodes.size() == 2 && "Expected a load folding node!");
  873. N = NewNodes[1];
  874. SDNode *LoadNode = NewNodes[0];
  875. unsigned NumVals = N->getNumValues();
  876. unsigned OldNumVals = SU->getNode()->getNumValues();
  877. // LoadNode may already exist. This can happen when there is another
  878. // load from the same location and producing the same type of value
  879. // but it has different alignment or volatileness.
  880. bool isNewLoad = true;
  881. SUnit *LoadSU;
  882. if (LoadNode->getNodeId() != -1) {
  883. LoadSU = &SUnits[LoadNode->getNodeId()];
  884. // If LoadSU has already been scheduled, we should clone it but
  885. // this would negate the benefit to unfolding so just return SU.
  886. if (LoadSU->isScheduled)
  887. return SU;
  888. isNewLoad = false;
  889. } else {
  890. LoadSU = CreateNewSUnit(LoadNode);
  891. LoadNode->setNodeId(LoadSU->NodeNum);
  892. InitNumRegDefsLeft(LoadSU);
  893. computeLatency(LoadSU);
  894. }
  895. bool isNewN = true;
  896. SUnit *NewSU;
  897. // This can only happen when isNewLoad is false.
  898. if (N->getNodeId() != -1) {
  899. NewSU = &SUnits[N->getNodeId()];
  900. // If NewSU has already been scheduled, we need to clone it, but this
  901. // negates the benefit to unfolding so just return SU.
  902. if (NewSU->isScheduled) {
  903. return SU;
  904. }
  905. isNewN = false;
  906. } else {
  907. NewSU = CreateNewSUnit(N);
  908. N->setNodeId(NewSU->NodeNum);
  909. const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
  910. for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
  911. if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
  912. NewSU->isTwoAddress = true;
  913. break;
  914. }
  915. }
  916. if (MCID.isCommutable())
  917. NewSU->isCommutable = true;
  918. InitNumRegDefsLeft(NewSU);
  919. computeLatency(NewSU);
  920. }
  921. LLVM_DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
  922. // Now that we are committed to unfolding replace DAG Uses.
  923. for (unsigned i = 0; i != NumVals; ++i)
  924. DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
  925. DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals - 1),
  926. SDValue(LoadNode, 1));
  927. // Record all the edges to and from the old SU, by category.
  928. SmallVector<SDep, 4> ChainPreds;
  929. SmallVector<SDep, 4> ChainSuccs;
  930. SmallVector<SDep, 4> LoadPreds;
  931. SmallVector<SDep, 4> NodePreds;
  932. SmallVector<SDep, 4> NodeSuccs;
  933. for (SDep &Pred : SU->Preds) {
  934. if (Pred.isCtrl())
  935. ChainPreds.push_back(Pred);
  936. else if (isOperandOf(Pred.getSUnit(), LoadNode))
  937. LoadPreds.push_back(Pred);
  938. else
  939. NodePreds.push_back(Pred);
  940. }
  941. for (SDep &Succ : SU->Succs) {
  942. if (Succ.isCtrl())
  943. ChainSuccs.push_back(Succ);
  944. else
  945. NodeSuccs.push_back(Succ);
  946. }
  947. // Now assign edges to the newly-created nodes.
  948. for (const SDep &Pred : ChainPreds) {
  949. RemovePred(SU, Pred);
  950. if (isNewLoad)
  951. AddPredQueued(LoadSU, Pred);
  952. }
  953. for (const SDep &Pred : LoadPreds) {
  954. RemovePred(SU, Pred);
  955. if (isNewLoad)
  956. AddPredQueued(LoadSU, Pred);
  957. }
  958. for (const SDep &Pred : NodePreds) {
  959. RemovePred(SU, Pred);
  960. AddPredQueued(NewSU, Pred);
  961. }
  962. for (SDep &D : NodeSuccs) {
  963. SUnit *SuccDep = D.getSUnit();
  964. D.setSUnit(SU);
  965. RemovePred(SuccDep, D);
  966. D.setSUnit(NewSU);
  967. AddPredQueued(SuccDep, D);
  968. // Balance register pressure.
  969. if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled &&
  970. !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
  971. --NewSU->NumRegDefsLeft;
  972. }
  973. for (SDep &D : ChainSuccs) {
  974. SUnit *SuccDep = D.getSUnit();
  975. D.setSUnit(SU);
  976. RemovePred(SuccDep, D);
  977. if (isNewLoad) {
  978. D.setSUnit(LoadSU);
  979. AddPredQueued(SuccDep, D);
  980. }
  981. }
  982. // Add a data dependency to reflect that NewSU reads the value defined
  983. // by LoadSU.
  984. SDep D(LoadSU, SDep::Data, 0);
  985. D.setLatency(LoadSU->Latency);
  986. AddPredQueued(NewSU, D);
  987. if (isNewLoad)
  988. AvailableQueue->addNode(LoadSU);
  989. if (isNewN)
  990. AvailableQueue->addNode(NewSU);
  991. ++NumUnfolds;
  992. if (NewSU->NumSuccsLeft == 0)
  993. NewSU->isAvailable = true;
  994. return NewSU;
  995. }
  996. /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
  997. /// successors to the newly created node.
  998. SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
  999. SDNode *N = SU->getNode();
  1000. if (!N)
  1001. return nullptr;
  1002. LLVM_DEBUG(dbgs() << "Considering duplicating the SU\n");
  1003. LLVM_DEBUG(dumpNode(*SU));
  1004. if (N->getGluedNode() &&
  1005. !TII->canCopyGluedNodeDuringSchedule(N)) {
  1006. LLVM_DEBUG(
  1007. dbgs()
  1008. << "Giving up because it has incoming glue and the target does not "
  1009. "want to copy it\n");
  1010. return nullptr;
  1011. }
  1012. SUnit *NewSU;
  1013. bool TryUnfold = false;
  1014. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
  1015. MVT VT = N->getSimpleValueType(i);
  1016. if (VT == MVT::Glue) {
  1017. LLVM_DEBUG(dbgs() << "Giving up because it has outgoing glue\n");
  1018. return nullptr;
  1019. } else if (VT == MVT::Other)
  1020. TryUnfold = true;
  1021. }
  1022. for (const SDValue &Op : N->op_values()) {
  1023. MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
  1024. if (VT == MVT::Glue && !TII->canCopyGluedNodeDuringSchedule(N)) {
  1025. LLVM_DEBUG(
  1026. dbgs() << "Giving up because it one of the operands is glue and "
  1027. "the target does not want to copy it\n");
  1028. return nullptr;
  1029. }
  1030. }
  1031. // If possible unfold instruction.
  1032. if (TryUnfold) {
  1033. SUnit *UnfoldSU = TryUnfoldSU(SU);
  1034. if (!UnfoldSU)
  1035. return nullptr;
  1036. SU = UnfoldSU;
  1037. N = SU->getNode();
  1038. // If this can be scheduled don't bother duplicating and just return
  1039. if (SU->NumSuccsLeft == 0)
  1040. return SU;
  1041. }
  1042. LLVM_DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
  1043. NewSU = CreateClone(SU);
  1044. // New SUnit has the exact same predecessors.
  1045. for (SDep &Pred : SU->Preds)
  1046. if (!Pred.isArtificial())
  1047. AddPredQueued(NewSU, Pred);
  1048. // Make sure the clone comes after the original. (InstrEmitter assumes
  1049. // this ordering.)
  1050. AddPredQueued(NewSU, SDep(SU, SDep::Artificial));
  1051. // Only copy scheduled successors. Cut them from old node's successor
  1052. // list and move them over.
  1053. SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
  1054. for (SDep &Succ : SU->Succs) {
  1055. if (Succ.isArtificial())
  1056. continue;
  1057. SUnit *SuccSU = Succ.getSUnit();
  1058. if (SuccSU->isScheduled) {
  1059. SDep D = Succ;
  1060. D.setSUnit(NewSU);
  1061. AddPredQueued(SuccSU, D);
  1062. D.setSUnit(SU);
  1063. DelDeps.emplace_back(SuccSU, D);
  1064. }
  1065. }
  1066. for (const auto &[DelSU, DelD] : DelDeps)
  1067. RemovePred(DelSU, DelD);
  1068. AvailableQueue->updateNode(SU);
  1069. AvailableQueue->addNode(NewSU);
  1070. ++NumDups;
  1071. return NewSU;
  1072. }
  1073. /// InsertCopiesAndMoveSuccs - Insert register copies and move all
  1074. /// scheduled successors of the given SUnit to the last copy.
  1075. void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
  1076. const TargetRegisterClass *DestRC,
  1077. const TargetRegisterClass *SrcRC,
  1078. SmallVectorImpl<SUnit*> &Copies) {
  1079. SUnit *CopyFromSU = CreateNewSUnit(nullptr);
  1080. CopyFromSU->CopySrcRC = SrcRC;
  1081. CopyFromSU->CopyDstRC = DestRC;
  1082. SUnit *CopyToSU = CreateNewSUnit(nullptr);
  1083. CopyToSU->CopySrcRC = DestRC;
  1084. CopyToSU->CopyDstRC = SrcRC;
  1085. // Only copy scheduled successors. Cut them from old node's successor
  1086. // list and move them over.
  1087. SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
  1088. for (SDep &Succ : SU->Succs) {
  1089. if (Succ.isArtificial())
  1090. continue;
  1091. SUnit *SuccSU = Succ.getSUnit();
  1092. if (SuccSU->isScheduled) {
  1093. SDep D = Succ;
  1094. D.setSUnit(CopyToSU);
  1095. AddPredQueued(SuccSU, D);
  1096. DelDeps.emplace_back(SuccSU, Succ);
  1097. }
  1098. else {
  1099. // Avoid scheduling the def-side copy before other successors. Otherwise,
  1100. // we could introduce another physreg interference on the copy and
  1101. // continue inserting copies indefinitely.
  1102. AddPredQueued(SuccSU, SDep(CopyFromSU, SDep::Artificial));
  1103. }
  1104. }
  1105. for (const auto &[DelSU, DelD] : DelDeps)
  1106. RemovePred(DelSU, DelD);
  1107. SDep FromDep(SU, SDep::Data, Reg);
  1108. FromDep.setLatency(SU->Latency);
  1109. AddPredQueued(CopyFromSU, FromDep);
  1110. SDep ToDep(CopyFromSU, SDep::Data, 0);
  1111. ToDep.setLatency(CopyFromSU->Latency);
  1112. AddPredQueued(CopyToSU, ToDep);
  1113. AvailableQueue->updateNode(SU);
  1114. AvailableQueue->addNode(CopyFromSU);
  1115. AvailableQueue->addNode(CopyToSU);
  1116. Copies.push_back(CopyFromSU);
  1117. Copies.push_back(CopyToSU);
  1118. ++NumPRCopies;
  1119. }
  1120. /// getPhysicalRegisterVT - Returns the ValueType of the physical register
  1121. /// definition of the specified node.
  1122. /// FIXME: Move to SelectionDAG?
  1123. static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
  1124. const TargetInstrInfo *TII) {
  1125. unsigned NumRes;
  1126. if (N->getOpcode() == ISD::CopyFromReg) {
  1127. // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
  1128. NumRes = 1;
  1129. } else {
  1130. const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
  1131. assert(!MCID.implicit_defs().empty() &&
  1132. "Physical reg def must be in implicit def list!");
  1133. NumRes = MCID.getNumDefs();
  1134. for (MCPhysReg ImpDef : MCID.implicit_defs()) {
  1135. if (Reg == ImpDef)
  1136. break;
  1137. ++NumRes;
  1138. }
  1139. }
  1140. return N->getSimpleValueType(NumRes);
  1141. }
  1142. /// CheckForLiveRegDef - Return true and update live register vector if the
  1143. /// specified register def of the specified SUnit clobbers any "live" registers.
  1144. static void CheckForLiveRegDef(SUnit *SU, unsigned Reg, SUnit **LiveRegDefs,
  1145. SmallSet<unsigned, 4> &RegAdded,
  1146. SmallVectorImpl<unsigned> &LRegs,
  1147. const TargetRegisterInfo *TRI,
  1148. const SDNode *Node = nullptr) {
  1149. for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
  1150. // Check if Ref is live.
  1151. if (!LiveRegDefs[*AliasI]) continue;
  1152. // Allow multiple uses of the same def.
  1153. if (LiveRegDefs[*AliasI] == SU) continue;
  1154. // Allow multiple uses of same def
  1155. if (Node && LiveRegDefs[*AliasI]->getNode() == Node)
  1156. continue;
  1157. // Add Reg to the set of interfering live regs.
  1158. if (RegAdded.insert(*AliasI).second) {
  1159. LRegs.push_back(*AliasI);
  1160. }
  1161. }
  1162. }
  1163. /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
  1164. /// by RegMask, and add them to LRegs.
  1165. static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
  1166. ArrayRef<SUnit*> LiveRegDefs,
  1167. SmallSet<unsigned, 4> &RegAdded,
  1168. SmallVectorImpl<unsigned> &LRegs) {
  1169. // Look at all live registers. Skip Reg0 and the special CallResource.
  1170. for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
  1171. if (!LiveRegDefs[i]) continue;
  1172. if (LiveRegDefs[i] == SU) continue;
  1173. if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
  1174. if (RegAdded.insert(i).second)
  1175. LRegs.push_back(i);
  1176. }
  1177. }
  1178. /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
  1179. static const uint32_t *getNodeRegMask(const SDNode *N) {
  1180. for (const SDValue &Op : N->op_values())
  1181. if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode()))
  1182. return RegOp->getRegMask();
  1183. return nullptr;
  1184. }
  1185. /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
  1186. /// scheduling of the given node to satisfy live physical register dependencies.
  1187. /// If the specific node is the last one that's available to schedule, do
  1188. /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
  1189. bool ScheduleDAGRRList::
  1190. DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
  1191. if (NumLiveRegs == 0)
  1192. return false;
  1193. SmallSet<unsigned, 4> RegAdded;
  1194. // If this node would clobber any "live" register, then it's not ready.
  1195. //
  1196. // If SU is the currently live definition of the same register that it uses,
  1197. // then we are free to schedule it.
  1198. for (SDep &Pred : SU->Preds) {
  1199. if (Pred.isAssignedRegDep() && LiveRegDefs[Pred.getReg()] != SU)
  1200. CheckForLiveRegDef(Pred.getSUnit(), Pred.getReg(), LiveRegDefs.get(),
  1201. RegAdded, LRegs, TRI);
  1202. }
  1203. for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
  1204. if (Node->getOpcode() == ISD::INLINEASM ||
  1205. Node->getOpcode() == ISD::INLINEASM_BR) {
  1206. // Inline asm can clobber physical defs.
  1207. unsigned NumOps = Node->getNumOperands();
  1208. if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
  1209. --NumOps; // Ignore the glue operand.
  1210. for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
  1211. unsigned Flags =
  1212. cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
  1213. unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
  1214. ++i; // Skip the ID value.
  1215. if (InlineAsm::isRegDefKind(Flags) ||
  1216. InlineAsm::isRegDefEarlyClobberKind(Flags) ||
  1217. InlineAsm::isClobberKind(Flags)) {
  1218. // Check for def of register or earlyclobber register.
  1219. for (; NumVals; --NumVals, ++i) {
  1220. Register Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
  1221. if (Reg.isPhysical())
  1222. CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
  1223. }
  1224. } else
  1225. i += NumVals;
  1226. }
  1227. continue;
  1228. }
  1229. if (Node->getOpcode() == ISD::CopyToReg) {
  1230. Register Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
  1231. if (Reg.isPhysical()) {
  1232. SDNode *SrcNode = Node->getOperand(2).getNode();
  1233. CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI,
  1234. SrcNode);
  1235. }
  1236. }
  1237. if (!Node->isMachineOpcode())
  1238. continue;
  1239. // If we're in the middle of scheduling a call, don't begin scheduling
  1240. // another call. Also, don't allow any physical registers to be live across
  1241. // the call.
  1242. if (Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
  1243. // Check the special calling-sequence resource.
  1244. unsigned CallResource = TRI->getNumRegs();
  1245. if (LiveRegDefs[CallResource]) {
  1246. SDNode *Gen = LiveRegGens[CallResource]->getNode();
  1247. while (SDNode *Glued = Gen->getGluedNode())
  1248. Gen = Glued;
  1249. if (!IsChainDependent(Gen, Node, 0, TII) &&
  1250. RegAdded.insert(CallResource).second)
  1251. LRegs.push_back(CallResource);
  1252. }
  1253. }
  1254. if (const uint32_t *RegMask = getNodeRegMask(Node))
  1255. CheckForLiveRegDefMasked(SU, RegMask,
  1256. ArrayRef(LiveRegDefs.get(), TRI->getNumRegs()),
  1257. RegAdded, LRegs);
  1258. const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
  1259. if (MCID.hasOptionalDef()) {
  1260. // Most ARM instructions have an OptionalDef for CPSR, to model the S-bit.
  1261. // This operand can be either a def of CPSR, if the S bit is set; or a use
  1262. // of %noreg. When the OptionalDef is set to a valid register, we need to
  1263. // handle it in the same way as an ImplicitDef.
  1264. for (unsigned i = 0; i < MCID.getNumDefs(); ++i)
  1265. if (MCID.operands()[i].isOptionalDef()) {
  1266. const SDValue &OptionalDef = Node->getOperand(i - Node->getNumValues());
  1267. Register Reg = cast<RegisterSDNode>(OptionalDef)->getReg();
  1268. CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
  1269. }
  1270. }
  1271. for (MCPhysReg Reg : MCID.implicit_defs())
  1272. CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
  1273. }
  1274. return !LRegs.empty();
  1275. }
  1276. void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
  1277. // Add the nodes that aren't ready back onto the available list.
  1278. for (unsigned i = Interferences.size(); i > 0; --i) {
  1279. SUnit *SU = Interferences[i-1];
  1280. LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
  1281. if (Reg) {
  1282. SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
  1283. if (!is_contained(LRegs, Reg))
  1284. continue;
  1285. }
  1286. SU->isPending = false;
  1287. // The interfering node may no longer be available due to backtracking.
  1288. // Furthermore, it may have been made available again, in which case it is
  1289. // now already in the AvailableQueue.
  1290. if (SU->isAvailable && !SU->NodeQueueId) {
  1291. LLVM_DEBUG(dbgs() << " Repushing SU #" << SU->NodeNum << '\n');
  1292. AvailableQueue->push(SU);
  1293. }
  1294. if (i < Interferences.size())
  1295. Interferences[i-1] = Interferences.back();
  1296. Interferences.pop_back();
  1297. LRegsMap.erase(LRegsPos);
  1298. }
  1299. }
  1300. /// Return a node that can be scheduled in this cycle. Requirements:
  1301. /// (1) Ready: latency has been satisfied
  1302. /// (2) No Hazards: resources are available
  1303. /// (3) No Interferences: may unschedule to break register interferences.
  1304. SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
  1305. SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
  1306. auto FindAvailableNode = [&]() {
  1307. while (CurSU) {
  1308. SmallVector<unsigned, 4> LRegs;
  1309. if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
  1310. break;
  1311. LLVM_DEBUG(dbgs() << " Interfering reg ";
  1312. if (LRegs[0] == TRI->getNumRegs()) dbgs() << "CallResource";
  1313. else dbgs() << printReg(LRegs[0], TRI);
  1314. dbgs() << " SU #" << CurSU->NodeNum << '\n');
  1315. auto [LRegsIter, LRegsInserted] = LRegsMap.try_emplace(CurSU, LRegs);
  1316. if (LRegsInserted) {
  1317. CurSU->isPending = true; // This SU is not in AvailableQueue right now.
  1318. Interferences.push_back(CurSU);
  1319. }
  1320. else {
  1321. assert(CurSU->isPending && "Interferences are pending");
  1322. // Update the interference with current live regs.
  1323. LRegsIter->second = LRegs;
  1324. }
  1325. CurSU = AvailableQueue->pop();
  1326. }
  1327. };
  1328. FindAvailableNode();
  1329. if (CurSU)
  1330. return CurSU;
  1331. // We query the topological order in the loop body, so make sure outstanding
  1332. // updates are applied before entering it (we only enter the loop if there
  1333. // are some interferences). If we make changes to the ordering, we exit
  1334. // the loop.
  1335. // All candidates are delayed due to live physical reg dependencies.
  1336. // Try backtracking, code duplication, or inserting cross class copies
  1337. // to resolve it.
  1338. for (SUnit *TrySU : Interferences) {
  1339. SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
  1340. // Try unscheduling up to the point where it's safe to schedule
  1341. // this node.
  1342. SUnit *BtSU = nullptr;
  1343. unsigned LiveCycle = std::numeric_limits<unsigned>::max();
  1344. for (unsigned Reg : LRegs) {
  1345. if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
  1346. BtSU = LiveRegGens[Reg];
  1347. LiveCycle = BtSU->getHeight();
  1348. }
  1349. }
  1350. if (!WillCreateCycle(TrySU, BtSU)) {
  1351. // BacktrackBottomUp mutates Interferences!
  1352. BacktrackBottomUp(TrySU, BtSU);
  1353. // Force the current node to be scheduled before the node that
  1354. // requires the physical reg dep.
  1355. if (BtSU->isAvailable) {
  1356. BtSU->isAvailable = false;
  1357. if (!BtSU->isPending)
  1358. AvailableQueue->remove(BtSU);
  1359. }
  1360. LLVM_DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum
  1361. << ") to SU(" << TrySU->NodeNum << ")\n");
  1362. AddPredQueued(TrySU, SDep(BtSU, SDep::Artificial));
  1363. // If one or more successors has been unscheduled, then the current
  1364. // node is no longer available.
  1365. if (!TrySU->isAvailable || !TrySU->NodeQueueId) {
  1366. LLVM_DEBUG(dbgs() << "TrySU not available; choosing node from queue\n");
  1367. CurSU = AvailableQueue->pop();
  1368. } else {
  1369. LLVM_DEBUG(dbgs() << "TrySU available\n");
  1370. // Available and in AvailableQueue
  1371. AvailableQueue->remove(TrySU);
  1372. CurSU = TrySU;
  1373. }
  1374. FindAvailableNode();
  1375. // Interferences has been mutated. We must break.
  1376. break;
  1377. }
  1378. }
  1379. if (!CurSU) {
  1380. // Can't backtrack. If it's too expensive to copy the value, then try
  1381. // duplicate the nodes that produces these "too expensive to copy"
  1382. // values to break the dependency. In case even that doesn't work,
  1383. // insert cross class copies.
  1384. // If it's not too expensive, i.e. cost != -1, issue copies.
  1385. SUnit *TrySU = Interferences[0];
  1386. SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
  1387. assert(LRegs.size() == 1 && "Can't handle this yet!");
  1388. unsigned Reg = LRegs[0];
  1389. SUnit *LRDef = LiveRegDefs[Reg];
  1390. MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
  1391. const TargetRegisterClass *RC =
  1392. TRI->getMinimalPhysRegClass(Reg, VT);
  1393. const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
  1394. // If cross copy register class is the same as RC, then it must be possible
  1395. // copy the value directly. Do not try duplicate the def.
  1396. // If cross copy register class is not the same as RC, then it's possible to
  1397. // copy the value but it require cross register class copies and it is
  1398. // expensive.
  1399. // If cross copy register class is null, then it's not possible to copy
  1400. // the value at all.
  1401. SUnit *NewDef = nullptr;
  1402. if (DestRC != RC) {
  1403. NewDef = CopyAndMoveSuccessors(LRDef);
  1404. if (!DestRC && !NewDef)
  1405. report_fatal_error("Can't handle live physical register dependency!");
  1406. }
  1407. if (!NewDef) {
  1408. // Issue copies, these can be expensive cross register class copies.
  1409. SmallVector<SUnit*, 2> Copies;
  1410. InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
  1411. LLVM_DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
  1412. << " to SU #" << Copies.front()->NodeNum << "\n");
  1413. AddPredQueued(TrySU, SDep(Copies.front(), SDep::Artificial));
  1414. NewDef = Copies.back();
  1415. }
  1416. LLVM_DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
  1417. << " to SU #" << TrySU->NodeNum << "\n");
  1418. LiveRegDefs[Reg] = NewDef;
  1419. AddPredQueued(NewDef, SDep(TrySU, SDep::Artificial));
  1420. TrySU->isAvailable = false;
  1421. CurSU = NewDef;
  1422. }
  1423. assert(CurSU && "Unable to resolve live physical register dependencies!");
  1424. return CurSU;
  1425. }
  1426. /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
  1427. /// schedulers.
  1428. void ScheduleDAGRRList::ListScheduleBottomUp() {
  1429. // Release any predecessors of the special Exit node.
  1430. ReleasePredecessors(&ExitSU);
  1431. // Add root to Available queue.
  1432. if (!SUnits.empty()) {
  1433. SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
  1434. assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
  1435. RootSU->isAvailable = true;
  1436. AvailableQueue->push(RootSU);
  1437. }
  1438. // While Available queue is not empty, grab the node with the highest
  1439. // priority. If it is not ready put it back. Schedule the node.
  1440. Sequence.reserve(SUnits.size());
  1441. while (!AvailableQueue->empty() || !Interferences.empty()) {
  1442. LLVM_DEBUG(dbgs() << "\nExamining Available:\n";
  1443. AvailableQueue->dump(this));
  1444. // Pick the best node to schedule taking all constraints into
  1445. // consideration.
  1446. SUnit *SU = PickNodeToScheduleBottomUp();
  1447. AdvancePastStalls(SU);
  1448. ScheduleNodeBottomUp(SU);
  1449. while (AvailableQueue->empty() && !PendingQueue.empty()) {
  1450. // Advance the cycle to free resources. Skip ahead to the next ready SU.
  1451. assert(MinAvailableCycle < std::numeric_limits<unsigned>::max() &&
  1452. "MinAvailableCycle uninitialized");
  1453. AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
  1454. }
  1455. }
  1456. // Reverse the order if it is bottom up.
  1457. std::reverse(Sequence.begin(), Sequence.end());
  1458. #ifndef NDEBUG
  1459. VerifyScheduledSequence(/*isBottomUp=*/true);
  1460. #endif
  1461. }
  1462. namespace {
  1463. class RegReductionPQBase;
  1464. struct queue_sort {
  1465. bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
  1466. };
  1467. #ifndef NDEBUG
  1468. template<class SF>
  1469. struct reverse_sort : public queue_sort {
  1470. SF &SortFunc;
  1471. reverse_sort(SF &sf) : SortFunc(sf) {}
  1472. bool operator()(SUnit* left, SUnit* right) const {
  1473. // reverse left/right rather than simply !SortFunc(left, right)
  1474. // to expose different paths in the comparison logic.
  1475. return SortFunc(right, left);
  1476. }
  1477. };
  1478. #endif // NDEBUG
  1479. /// bu_ls_rr_sort - Priority function for bottom up register pressure
  1480. // reduction scheduler.
  1481. struct bu_ls_rr_sort : public queue_sort {
  1482. enum {
  1483. IsBottomUp = true,
  1484. HasReadyFilter = false
  1485. };
  1486. RegReductionPQBase *SPQ;
  1487. bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1488. bool operator()(SUnit* left, SUnit* right) const;
  1489. };
  1490. // src_ls_rr_sort - Priority function for source order scheduler.
  1491. struct src_ls_rr_sort : public queue_sort {
  1492. enum {
  1493. IsBottomUp = true,
  1494. HasReadyFilter = false
  1495. };
  1496. RegReductionPQBase *SPQ;
  1497. src_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1498. bool operator()(SUnit* left, SUnit* right) const;
  1499. };
  1500. // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
  1501. struct hybrid_ls_rr_sort : public queue_sort {
  1502. enum {
  1503. IsBottomUp = true,
  1504. HasReadyFilter = false
  1505. };
  1506. RegReductionPQBase *SPQ;
  1507. hybrid_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1508. bool isReady(SUnit *SU, unsigned CurCycle) const;
  1509. bool operator()(SUnit* left, SUnit* right) const;
  1510. };
  1511. // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
  1512. // scheduler.
  1513. struct ilp_ls_rr_sort : public queue_sort {
  1514. enum {
  1515. IsBottomUp = true,
  1516. HasReadyFilter = false
  1517. };
  1518. RegReductionPQBase *SPQ;
  1519. ilp_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
  1520. bool isReady(SUnit *SU, unsigned CurCycle) const;
  1521. bool operator()(SUnit* left, SUnit* right) const;
  1522. };
  1523. class RegReductionPQBase : public SchedulingPriorityQueue {
  1524. protected:
  1525. std::vector<SUnit *> Queue;
  1526. unsigned CurQueueId = 0;
  1527. bool TracksRegPressure;
  1528. bool SrcOrder;
  1529. // SUnits - The SUnits for the current graph.
  1530. std::vector<SUnit> *SUnits;
  1531. MachineFunction &MF;
  1532. const TargetInstrInfo *TII;
  1533. const TargetRegisterInfo *TRI;
  1534. const TargetLowering *TLI;
  1535. ScheduleDAGRRList *scheduleDAG = nullptr;
  1536. // SethiUllmanNumbers - The SethiUllman number for each node.
  1537. std::vector<unsigned> SethiUllmanNumbers;
  1538. /// RegPressure - Tracking current reg pressure per register class.
  1539. std::vector<unsigned> RegPressure;
  1540. /// RegLimit - Tracking the number of allocatable registers per register
  1541. /// class.
  1542. std::vector<unsigned> RegLimit;
  1543. public:
  1544. RegReductionPQBase(MachineFunction &mf,
  1545. bool hasReadyFilter,
  1546. bool tracksrp,
  1547. bool srcorder,
  1548. const TargetInstrInfo *tii,
  1549. const TargetRegisterInfo *tri,
  1550. const TargetLowering *tli)
  1551. : SchedulingPriorityQueue(hasReadyFilter), TracksRegPressure(tracksrp),
  1552. SrcOrder(srcorder), MF(mf), TII(tii), TRI(tri), TLI(tli) {
  1553. if (TracksRegPressure) {
  1554. unsigned NumRC = TRI->getNumRegClasses();
  1555. RegLimit.resize(NumRC);
  1556. RegPressure.resize(NumRC);
  1557. std::fill(RegLimit.begin(), RegLimit.end(), 0);
  1558. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  1559. for (const TargetRegisterClass *RC : TRI->regclasses())
  1560. RegLimit[RC->getID()] = tri->getRegPressureLimit(RC, MF);
  1561. }
  1562. }
  1563. void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
  1564. scheduleDAG = scheduleDag;
  1565. }
  1566. ScheduleHazardRecognizer* getHazardRec() {
  1567. return scheduleDAG->getHazardRec();
  1568. }
  1569. void initNodes(std::vector<SUnit> &sunits) override;
  1570. void addNode(const SUnit *SU) override;
  1571. void updateNode(const SUnit *SU) override;
  1572. void releaseState() override {
  1573. SUnits = nullptr;
  1574. SethiUllmanNumbers.clear();
  1575. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  1576. }
  1577. unsigned getNodePriority(const SUnit *SU) const;
  1578. unsigned getNodeOrdering(const SUnit *SU) const {
  1579. if (!SU->getNode()) return 0;
  1580. return SU->getNode()->getIROrder();
  1581. }
  1582. bool empty() const override { return Queue.empty(); }
  1583. void push(SUnit *U) override {
  1584. assert(!U->NodeQueueId && "Node in the queue already");
  1585. U->NodeQueueId = ++CurQueueId;
  1586. Queue.push_back(U);
  1587. }
  1588. void remove(SUnit *SU) override {
  1589. assert(!Queue.empty() && "Queue is empty!");
  1590. assert(SU->NodeQueueId != 0 && "Not in queue!");
  1591. std::vector<SUnit *>::iterator I = llvm::find(Queue, SU);
  1592. if (I != std::prev(Queue.end()))
  1593. std::swap(*I, Queue.back());
  1594. Queue.pop_back();
  1595. SU->NodeQueueId = 0;
  1596. }
  1597. bool tracksRegPressure() const override { return TracksRegPressure; }
  1598. void dumpRegPressure() const;
  1599. bool HighRegPressure(const SUnit *SU) const;
  1600. bool MayReduceRegPressure(SUnit *SU) const;
  1601. int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
  1602. void scheduledNode(SUnit *SU) override;
  1603. void unscheduledNode(SUnit *SU) override;
  1604. protected:
  1605. bool canClobber(const SUnit *SU, const SUnit *Op);
  1606. void AddPseudoTwoAddrDeps();
  1607. void PrescheduleNodesWithMultipleUses();
  1608. void CalculateSethiUllmanNumbers();
  1609. };
  1610. template<class SF>
  1611. static SUnit *popFromQueueImpl(std::vector<SUnit *> &Q, SF &Picker) {
  1612. unsigned BestIdx = 0;
  1613. // Only compute the cost for the first 1000 items in the queue, to avoid
  1614. // excessive compile-times for very large queues.
  1615. for (unsigned I = 1, E = std::min(Q.size(), (decltype(Q.size()))1000); I != E;
  1616. I++)
  1617. if (Picker(Q[BestIdx], Q[I]))
  1618. BestIdx = I;
  1619. SUnit *V = Q[BestIdx];
  1620. if (BestIdx + 1 != Q.size())
  1621. std::swap(Q[BestIdx], Q.back());
  1622. Q.pop_back();
  1623. return V;
  1624. }
  1625. template<class SF>
  1626. SUnit *popFromQueue(std::vector<SUnit *> &Q, SF &Picker, ScheduleDAG *DAG) {
  1627. #ifndef NDEBUG
  1628. if (DAG->StressSched) {
  1629. reverse_sort<SF> RPicker(Picker);
  1630. return popFromQueueImpl(Q, RPicker);
  1631. }
  1632. #endif
  1633. (void)DAG;
  1634. return popFromQueueImpl(Q, Picker);
  1635. }
  1636. //===----------------------------------------------------------------------===//
  1637. // RegReductionPriorityQueue Definition
  1638. //===----------------------------------------------------------------------===//
  1639. //
  1640. // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
  1641. // to reduce register pressure.
  1642. //
  1643. template<class SF>
  1644. class RegReductionPriorityQueue : public RegReductionPQBase {
  1645. SF Picker;
  1646. public:
  1647. RegReductionPriorityQueue(MachineFunction &mf,
  1648. bool tracksrp,
  1649. bool srcorder,
  1650. const TargetInstrInfo *tii,
  1651. const TargetRegisterInfo *tri,
  1652. const TargetLowering *tli)
  1653. : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
  1654. tii, tri, tli),
  1655. Picker(this) {}
  1656. bool isBottomUp() const override { return SF::IsBottomUp; }
  1657. bool isReady(SUnit *U) const override {
  1658. return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
  1659. }
  1660. SUnit *pop() override {
  1661. if (Queue.empty()) return nullptr;
  1662. SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
  1663. V->NodeQueueId = 0;
  1664. return V;
  1665. }
  1666. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1667. LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override {
  1668. // Emulate pop() without clobbering NodeQueueIds.
  1669. std::vector<SUnit *> DumpQueue = Queue;
  1670. SF DumpPicker = Picker;
  1671. while (!DumpQueue.empty()) {
  1672. SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
  1673. dbgs() << "Height " << SU->getHeight() << ": ";
  1674. DAG->dumpNode(*SU);
  1675. }
  1676. }
  1677. #endif
  1678. };
  1679. using BURegReductionPriorityQueue = RegReductionPriorityQueue<bu_ls_rr_sort>;
  1680. using SrcRegReductionPriorityQueue = RegReductionPriorityQueue<src_ls_rr_sort>;
  1681. using HybridBURRPriorityQueue = RegReductionPriorityQueue<hybrid_ls_rr_sort>;
  1682. using ILPBURRPriorityQueue = RegReductionPriorityQueue<ilp_ls_rr_sort>;
  1683. } // end anonymous namespace
  1684. //===----------------------------------------------------------------------===//
  1685. // Static Node Priority for Register Pressure Reduction
  1686. //===----------------------------------------------------------------------===//
  1687. // Check for special nodes that bypass scheduling heuristics.
  1688. // Currently this pushes TokenFactor nodes down, but may be used for other
  1689. // pseudo-ops as well.
  1690. //
  1691. // Return -1 to schedule right above left, 1 for left above right.
  1692. // Return 0 if no bias exists.
  1693. static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
  1694. bool LSchedLow = left->isScheduleLow;
  1695. bool RSchedLow = right->isScheduleLow;
  1696. if (LSchedLow != RSchedLow)
  1697. return LSchedLow < RSchedLow ? 1 : -1;
  1698. return 0;
  1699. }
  1700. /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
  1701. /// Smaller number is the higher priority.
  1702. static unsigned
  1703. CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
  1704. if (SUNumbers[SU->NodeNum] != 0)
  1705. return SUNumbers[SU->NodeNum];
  1706. // Use WorkList to avoid stack overflow on excessively large IRs.
  1707. struct WorkState {
  1708. WorkState(const SUnit *SU) : SU(SU) {}
  1709. const SUnit *SU;
  1710. unsigned PredsProcessed = 0;
  1711. };
  1712. SmallVector<WorkState, 16> WorkList;
  1713. WorkList.push_back(SU);
  1714. while (!WorkList.empty()) {
  1715. auto &Temp = WorkList.back();
  1716. auto *TempSU = Temp.SU;
  1717. bool AllPredsKnown = true;
  1718. // Try to find a non-evaluated pred and push it into the processing stack.
  1719. for (unsigned P = Temp.PredsProcessed; P < TempSU->Preds.size(); ++P) {
  1720. auto &Pred = TempSU->Preds[P];
  1721. if (Pred.isCtrl()) continue; // ignore chain preds
  1722. SUnit *PredSU = Pred.getSUnit();
  1723. if (SUNumbers[PredSU->NodeNum] == 0) {
  1724. #ifndef NDEBUG
  1725. // In debug mode, check that we don't have such element in the stack.
  1726. for (auto It : WorkList)
  1727. assert(It.SU != PredSU && "Trying to push an element twice?");
  1728. #endif
  1729. // Next time start processing this one starting from the next pred.
  1730. Temp.PredsProcessed = P + 1;
  1731. WorkList.push_back(PredSU);
  1732. AllPredsKnown = false;
  1733. break;
  1734. }
  1735. }
  1736. if (!AllPredsKnown)
  1737. continue;
  1738. // Once all preds are known, we can calculate the answer for this one.
  1739. unsigned SethiUllmanNumber = 0;
  1740. unsigned Extra = 0;
  1741. for (const SDep &Pred : TempSU->Preds) {
  1742. if (Pred.isCtrl()) continue; // ignore chain preds
  1743. SUnit *PredSU = Pred.getSUnit();
  1744. unsigned PredSethiUllman = SUNumbers[PredSU->NodeNum];
  1745. assert(PredSethiUllman > 0 && "We should have evaluated this pred!");
  1746. if (PredSethiUllman > SethiUllmanNumber) {
  1747. SethiUllmanNumber = PredSethiUllman;
  1748. Extra = 0;
  1749. } else if (PredSethiUllman == SethiUllmanNumber)
  1750. ++Extra;
  1751. }
  1752. SethiUllmanNumber += Extra;
  1753. if (SethiUllmanNumber == 0)
  1754. SethiUllmanNumber = 1;
  1755. SUNumbers[TempSU->NodeNum] = SethiUllmanNumber;
  1756. WorkList.pop_back();
  1757. }
  1758. assert(SUNumbers[SU->NodeNum] > 0 && "SethiUllman should never be zero!");
  1759. return SUNumbers[SU->NodeNum];
  1760. }
  1761. /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
  1762. /// scheduling units.
  1763. void RegReductionPQBase::CalculateSethiUllmanNumbers() {
  1764. SethiUllmanNumbers.assign(SUnits->size(), 0);
  1765. for (const SUnit &SU : *SUnits)
  1766. CalcNodeSethiUllmanNumber(&SU, SethiUllmanNumbers);
  1767. }
  1768. void RegReductionPQBase::addNode(const SUnit *SU) {
  1769. unsigned SUSize = SethiUllmanNumbers.size();
  1770. if (SUnits->size() > SUSize)
  1771. SethiUllmanNumbers.resize(SUSize*2, 0);
  1772. CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
  1773. }
  1774. void RegReductionPQBase::updateNode(const SUnit *SU) {
  1775. SethiUllmanNumbers[SU->NodeNum] = 0;
  1776. CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
  1777. }
  1778. // Lower priority means schedule further down. For bottom-up scheduling, lower
  1779. // priority SUs are scheduled before higher priority SUs.
  1780. unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
  1781. assert(SU->NodeNum < SethiUllmanNumbers.size());
  1782. unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
  1783. if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
  1784. // CopyToReg should be close to its uses to facilitate coalescing and
  1785. // avoid spilling.
  1786. return 0;
  1787. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  1788. Opc == TargetOpcode::SUBREG_TO_REG ||
  1789. Opc == TargetOpcode::INSERT_SUBREG)
  1790. // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
  1791. // close to their uses to facilitate coalescing.
  1792. return 0;
  1793. if (SU->NumSuccs == 0 && SU->NumPreds != 0)
  1794. // If SU does not have a register use, i.e. it doesn't produce a value
  1795. // that would be consumed (e.g. store), then it terminates a chain of
  1796. // computation. Give it a large SethiUllman number so it will be
  1797. // scheduled right before its predecessors that it doesn't lengthen
  1798. // their live ranges.
  1799. return 0xffff;
  1800. if (SU->NumPreds == 0 && SU->NumSuccs != 0)
  1801. // If SU does not have a register def, schedule it close to its uses
  1802. // because it does not lengthen any live ranges.
  1803. return 0;
  1804. #if 1
  1805. return SethiUllmanNumbers[SU->NodeNum];
  1806. #else
  1807. unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
  1808. if (SU->isCallOp) {
  1809. // FIXME: This assumes all of the defs are used as call operands.
  1810. int NP = (int)Priority - SU->getNode()->getNumValues();
  1811. return (NP > 0) ? NP : 0;
  1812. }
  1813. return Priority;
  1814. #endif
  1815. }
  1816. //===----------------------------------------------------------------------===//
  1817. // Register Pressure Tracking
  1818. //===----------------------------------------------------------------------===//
  1819. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1820. LLVM_DUMP_METHOD void RegReductionPQBase::dumpRegPressure() const {
  1821. for (const TargetRegisterClass *RC : TRI->regclasses()) {
  1822. unsigned Id = RC->getID();
  1823. unsigned RP = RegPressure[Id];
  1824. if (!RP) continue;
  1825. LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
  1826. << RegLimit[Id] << '\n');
  1827. }
  1828. }
  1829. #endif
  1830. bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
  1831. if (!TLI)
  1832. return false;
  1833. for (const SDep &Pred : SU->Preds) {
  1834. if (Pred.isCtrl())
  1835. continue;
  1836. SUnit *PredSU = Pred.getSUnit();
  1837. // NumRegDefsLeft is zero when enough uses of this node have been scheduled
  1838. // to cover the number of registers defined (they are all live).
  1839. if (PredSU->NumRegDefsLeft == 0) {
  1840. continue;
  1841. }
  1842. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
  1843. RegDefPos.IsValid(); RegDefPos.Advance()) {
  1844. unsigned RCId, Cost;
  1845. GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
  1846. if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
  1847. return true;
  1848. }
  1849. }
  1850. return false;
  1851. }
  1852. bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
  1853. const SDNode *N = SU->getNode();
  1854. if (!N->isMachineOpcode() || !SU->NumSuccs)
  1855. return false;
  1856. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  1857. for (unsigned i = 0; i != NumDefs; ++i) {
  1858. MVT VT = N->getSimpleValueType(i);
  1859. if (!N->hasAnyUseOfValue(i))
  1860. continue;
  1861. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1862. if (RegPressure[RCId] >= RegLimit[RCId])
  1863. return true;
  1864. }
  1865. return false;
  1866. }
  1867. // Compute the register pressure contribution by this instruction by count up
  1868. // for uses that are not live and down for defs. Only count register classes
  1869. // that are already under high pressure. As a side effect, compute the number of
  1870. // uses of registers that are already live.
  1871. //
  1872. // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
  1873. // so could probably be factored.
  1874. int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
  1875. LiveUses = 0;
  1876. int PDiff = 0;
  1877. for (const SDep &Pred : SU->Preds) {
  1878. if (Pred.isCtrl())
  1879. continue;
  1880. SUnit *PredSU = Pred.getSUnit();
  1881. // NumRegDefsLeft is zero when enough uses of this node have been scheduled
  1882. // to cover the number of registers defined (they are all live).
  1883. if (PredSU->NumRegDefsLeft == 0) {
  1884. if (PredSU->getNode()->isMachineOpcode())
  1885. ++LiveUses;
  1886. continue;
  1887. }
  1888. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
  1889. RegDefPos.IsValid(); RegDefPos.Advance()) {
  1890. MVT VT = RegDefPos.GetValue();
  1891. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1892. if (RegPressure[RCId] >= RegLimit[RCId])
  1893. ++PDiff;
  1894. }
  1895. }
  1896. const SDNode *N = SU->getNode();
  1897. if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
  1898. return PDiff;
  1899. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  1900. for (unsigned i = 0; i != NumDefs; ++i) {
  1901. MVT VT = N->getSimpleValueType(i);
  1902. if (!N->hasAnyUseOfValue(i))
  1903. continue;
  1904. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  1905. if (RegPressure[RCId] >= RegLimit[RCId])
  1906. --PDiff;
  1907. }
  1908. return PDiff;
  1909. }
  1910. void RegReductionPQBase::scheduledNode(SUnit *SU) {
  1911. if (!TracksRegPressure)
  1912. return;
  1913. if (!SU->getNode())
  1914. return;
  1915. for (const SDep &Pred : SU->Preds) {
  1916. if (Pred.isCtrl())
  1917. continue;
  1918. SUnit *PredSU = Pred.getSUnit();
  1919. // NumRegDefsLeft is zero when enough uses of this node have been scheduled
  1920. // to cover the number of registers defined (they are all live).
  1921. if (PredSU->NumRegDefsLeft == 0) {
  1922. continue;
  1923. }
  1924. // FIXME: The ScheduleDAG currently loses information about which of a
  1925. // node's values is consumed by each dependence. Consequently, if the node
  1926. // defines multiple register classes, we don't know which to pressurize
  1927. // here. Instead the following loop consumes the register defs in an
  1928. // arbitrary order. At least it handles the common case of clustered loads
  1929. // to the same class. For precise liveness, each SDep needs to indicate the
  1930. // result number. But that tightly couples the ScheduleDAG with the
  1931. // SelectionDAG making updates tricky. A simpler hack would be to attach a
  1932. // value type or register class to SDep.
  1933. //
  1934. // The most important aspect of register tracking is balancing the increase
  1935. // here with the reduction further below. Note that this SU may use multiple
  1936. // defs in PredSU. The can't be determined here, but we've already
  1937. // compensated by reducing NumRegDefsLeft in PredSU during
  1938. // ScheduleDAGSDNodes::AddSchedEdges.
  1939. --PredSU->NumRegDefsLeft;
  1940. unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
  1941. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
  1942. RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
  1943. if (SkipRegDefs)
  1944. continue;
  1945. unsigned RCId, Cost;
  1946. GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
  1947. RegPressure[RCId] += Cost;
  1948. break;
  1949. }
  1950. }
  1951. // We should have this assert, but there may be dead SDNodes that never
  1952. // materialize as SUnits, so they don't appear to generate liveness.
  1953. //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
  1954. int SkipRegDefs = (int)SU->NumRegDefsLeft;
  1955. for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
  1956. RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
  1957. if (SkipRegDefs > 0)
  1958. continue;
  1959. unsigned RCId, Cost;
  1960. GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
  1961. if (RegPressure[RCId] < Cost) {
  1962. // Register pressure tracking is imprecise. This can happen. But we try
  1963. // hard not to let it happen because it likely results in poor scheduling.
  1964. LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum
  1965. << ") has too many regdefs\n");
  1966. RegPressure[RCId] = 0;
  1967. }
  1968. else {
  1969. RegPressure[RCId] -= Cost;
  1970. }
  1971. }
  1972. LLVM_DEBUG(dumpRegPressure());
  1973. }
  1974. void RegReductionPQBase::unscheduledNode(SUnit *SU) {
  1975. if (!TracksRegPressure)
  1976. return;
  1977. const SDNode *N = SU->getNode();
  1978. if (!N) return;
  1979. if (!N->isMachineOpcode()) {
  1980. if (N->getOpcode() != ISD::CopyToReg)
  1981. return;
  1982. } else {
  1983. unsigned Opc = N->getMachineOpcode();
  1984. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  1985. Opc == TargetOpcode::INSERT_SUBREG ||
  1986. Opc == TargetOpcode::SUBREG_TO_REG ||
  1987. Opc == TargetOpcode::REG_SEQUENCE ||
  1988. Opc == TargetOpcode::IMPLICIT_DEF)
  1989. return;
  1990. }
  1991. for (const SDep &Pred : SU->Preds) {
  1992. if (Pred.isCtrl())
  1993. continue;
  1994. SUnit *PredSU = Pred.getSUnit();
  1995. // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
  1996. // counts data deps.
  1997. if (PredSU->NumSuccsLeft != PredSU->Succs.size())
  1998. continue;
  1999. const SDNode *PN = PredSU->getNode();
  2000. if (!PN->isMachineOpcode()) {
  2001. if (PN->getOpcode() == ISD::CopyFromReg) {
  2002. MVT VT = PN->getSimpleValueType(0);
  2003. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  2004. RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
  2005. }
  2006. continue;
  2007. }
  2008. unsigned POpc = PN->getMachineOpcode();
  2009. if (POpc == TargetOpcode::IMPLICIT_DEF)
  2010. continue;
  2011. if (POpc == TargetOpcode::EXTRACT_SUBREG ||
  2012. POpc == TargetOpcode::INSERT_SUBREG ||
  2013. POpc == TargetOpcode::SUBREG_TO_REG) {
  2014. MVT VT = PN->getSimpleValueType(0);
  2015. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  2016. RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
  2017. continue;
  2018. }
  2019. if (POpc == TargetOpcode::REG_SEQUENCE) {
  2020. unsigned DstRCIdx =
  2021. cast<ConstantSDNode>(PN->getOperand(0))->getZExtValue();
  2022. const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
  2023. unsigned RCId = RC->getID();
  2024. // REG_SEQUENCE is untyped, so getRepRegClassCostFor could not be used
  2025. // here. Instead use the same constant as in GetCostForDef.
  2026. RegPressure[RCId] += RegSequenceCost;
  2027. continue;
  2028. }
  2029. unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
  2030. for (unsigned i = 0; i != NumDefs; ++i) {
  2031. MVT VT = PN->getSimpleValueType(i);
  2032. if (!PN->hasAnyUseOfValue(i))
  2033. continue;
  2034. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  2035. if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
  2036. // Register pressure tracking is imprecise. This can happen.
  2037. RegPressure[RCId] = 0;
  2038. else
  2039. RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
  2040. }
  2041. }
  2042. // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
  2043. // may transfer data dependencies to CopyToReg.
  2044. if (SU->NumSuccs && N->isMachineOpcode()) {
  2045. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  2046. for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
  2047. MVT VT = N->getSimpleValueType(i);
  2048. if (VT == MVT::Glue || VT == MVT::Other)
  2049. continue;
  2050. if (!N->hasAnyUseOfValue(i))
  2051. continue;
  2052. unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
  2053. RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
  2054. }
  2055. }
  2056. LLVM_DEBUG(dumpRegPressure());
  2057. }
  2058. //===----------------------------------------------------------------------===//
  2059. // Dynamic Node Priority for Register Pressure Reduction
  2060. //===----------------------------------------------------------------------===//
  2061. /// closestSucc - Returns the scheduled cycle of the successor which is
  2062. /// closest to the current cycle.
  2063. static unsigned closestSucc(const SUnit *SU) {
  2064. unsigned MaxHeight = 0;
  2065. for (const SDep &Succ : SU->Succs) {
  2066. if (Succ.isCtrl()) continue; // ignore chain succs
  2067. unsigned Height = Succ.getSUnit()->getHeight();
  2068. // If there are bunch of CopyToRegs stacked up, they should be considered
  2069. // to be at the same position.
  2070. if (Succ.getSUnit()->getNode() &&
  2071. Succ.getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
  2072. Height = closestSucc(Succ.getSUnit())+1;
  2073. if (Height > MaxHeight)
  2074. MaxHeight = Height;
  2075. }
  2076. return MaxHeight;
  2077. }
  2078. /// calcMaxScratches - Returns an cost estimate of the worse case requirement
  2079. /// for scratch registers, i.e. number of data dependencies.
  2080. static unsigned calcMaxScratches(const SUnit *SU) {
  2081. unsigned Scratches = 0;
  2082. for (const SDep &Pred : SU->Preds) {
  2083. if (Pred.isCtrl()) continue; // ignore chain preds
  2084. Scratches++;
  2085. }
  2086. return Scratches;
  2087. }
  2088. /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
  2089. /// CopyFromReg from a virtual register.
  2090. static bool hasOnlyLiveInOpers(const SUnit *SU) {
  2091. bool RetVal = false;
  2092. for (const SDep &Pred : SU->Preds) {
  2093. if (Pred.isCtrl()) continue;
  2094. const SUnit *PredSU = Pred.getSUnit();
  2095. if (PredSU->getNode() &&
  2096. PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
  2097. Register Reg =
  2098. cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
  2099. if (Reg.isVirtual()) {
  2100. RetVal = true;
  2101. continue;
  2102. }
  2103. }
  2104. return false;
  2105. }
  2106. return RetVal;
  2107. }
  2108. /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
  2109. /// CopyToReg to a virtual register. This SU def is probably a liveout and
  2110. /// it has no other use. It should be scheduled closer to the terminator.
  2111. static bool hasOnlyLiveOutUses(const SUnit *SU) {
  2112. bool RetVal = false;
  2113. for (const SDep &Succ : SU->Succs) {
  2114. if (Succ.isCtrl()) continue;
  2115. const SUnit *SuccSU = Succ.getSUnit();
  2116. if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
  2117. Register Reg =
  2118. cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
  2119. if (Reg.isVirtual()) {
  2120. RetVal = true;
  2121. continue;
  2122. }
  2123. }
  2124. return false;
  2125. }
  2126. return RetVal;
  2127. }
  2128. // Set isVRegCycle for a node with only live in opers and live out uses. Also
  2129. // set isVRegCycle for its CopyFromReg operands.
  2130. //
  2131. // This is only relevant for single-block loops, in which case the VRegCycle
  2132. // node is likely an induction variable in which the operand and target virtual
  2133. // registers should be coalesced (e.g. pre/post increment values). Setting the
  2134. // isVRegCycle flag helps the scheduler prioritize other uses of the same
  2135. // CopyFromReg so that this node becomes the virtual register "kill". This
  2136. // avoids interference between the values live in and out of the block and
  2137. // eliminates a copy inside the loop.
  2138. static void initVRegCycle(SUnit *SU) {
  2139. if (DisableSchedVRegCycle)
  2140. return;
  2141. if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
  2142. return;
  2143. LLVM_DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
  2144. SU->isVRegCycle = true;
  2145. for (const SDep &Pred : SU->Preds) {
  2146. if (Pred.isCtrl()) continue;
  2147. Pred.getSUnit()->isVRegCycle = true;
  2148. }
  2149. }
  2150. // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
  2151. // CopyFromReg operands. We should no longer penalize other uses of this VReg.
  2152. static void resetVRegCycle(SUnit *SU) {
  2153. if (!SU->isVRegCycle)
  2154. return;
  2155. for (const SDep &Pred : SU->Preds) {
  2156. if (Pred.isCtrl()) continue; // ignore chain preds
  2157. SUnit *PredSU = Pred.getSUnit();
  2158. if (PredSU->isVRegCycle) {
  2159. assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
  2160. "VRegCycle def must be CopyFromReg");
  2161. Pred.getSUnit()->isVRegCycle = false;
  2162. }
  2163. }
  2164. }
  2165. // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
  2166. // means a node that defines the VRegCycle has not been scheduled yet.
  2167. static bool hasVRegCycleUse(const SUnit *SU) {
  2168. // If this SU also defines the VReg, don't hoist it as a "use".
  2169. if (SU->isVRegCycle)
  2170. return false;
  2171. for (const SDep &Pred : SU->Preds) {
  2172. if (Pred.isCtrl()) continue; // ignore chain preds
  2173. if (Pred.getSUnit()->isVRegCycle &&
  2174. Pred.getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
  2175. LLVM_DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
  2176. return true;
  2177. }
  2178. }
  2179. return false;
  2180. }
  2181. // Check for either a dependence (latency) or resource (hazard) stall.
  2182. //
  2183. // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
  2184. static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
  2185. if ((int)SPQ->getCurCycle() < Height) return true;
  2186. if (SPQ->getHazardRec()->getHazardType(SU, 0)
  2187. != ScheduleHazardRecognizer::NoHazard)
  2188. return true;
  2189. return false;
  2190. }
  2191. // Return -1 if left has higher priority, 1 if right has higher priority.
  2192. // Return 0 if latency-based priority is equivalent.
  2193. static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
  2194. RegReductionPQBase *SPQ) {
  2195. // Scheduling an instruction that uses a VReg whose postincrement has not yet
  2196. // been scheduled will induce a copy. Model this as an extra cycle of latency.
  2197. int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
  2198. int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
  2199. int LHeight = (int)left->getHeight() + LPenalty;
  2200. int RHeight = (int)right->getHeight() + RPenalty;
  2201. bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
  2202. BUHasStall(left, LHeight, SPQ);
  2203. bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
  2204. BUHasStall(right, RHeight, SPQ);
  2205. // If scheduling one of the node will cause a pipeline stall, delay it.
  2206. // If scheduling either one of the node will cause a pipeline stall, sort
  2207. // them according to their height.
  2208. if (LStall) {
  2209. if (!RStall)
  2210. return 1;
  2211. if (LHeight != RHeight)
  2212. return LHeight > RHeight ? 1 : -1;
  2213. } else if (RStall)
  2214. return -1;
  2215. // If either node is scheduling for latency, sort them by height/depth
  2216. // and latency.
  2217. if (!checkPref || (left->SchedulingPref == Sched::ILP ||
  2218. right->SchedulingPref == Sched::ILP)) {
  2219. // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
  2220. // is enabled, grouping instructions by cycle, then its height is already
  2221. // covered so only its depth matters. We also reach this point if both stall
  2222. // but have the same height.
  2223. if (!SPQ->getHazardRec()->isEnabled()) {
  2224. if (LHeight != RHeight)
  2225. return LHeight > RHeight ? 1 : -1;
  2226. }
  2227. int LDepth = left->getDepth() - LPenalty;
  2228. int RDepth = right->getDepth() - RPenalty;
  2229. if (LDepth != RDepth) {
  2230. LLVM_DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
  2231. << ") depth " << LDepth << " vs SU (" << right->NodeNum
  2232. << ") depth " << RDepth << "\n");
  2233. return LDepth < RDepth ? 1 : -1;
  2234. }
  2235. if (left->Latency != right->Latency)
  2236. return left->Latency > right->Latency ? 1 : -1;
  2237. }
  2238. return 0;
  2239. }
  2240. static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
  2241. // Schedule physical register definitions close to their use. This is
  2242. // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
  2243. // long as shortening physreg live ranges is generally good, we can defer
  2244. // creating a subtarget hook.
  2245. if (!DisableSchedPhysRegJoin) {
  2246. bool LHasPhysReg = left->hasPhysRegDefs;
  2247. bool RHasPhysReg = right->hasPhysRegDefs;
  2248. if (LHasPhysReg != RHasPhysReg) {
  2249. #ifndef NDEBUG
  2250. static const char *const PhysRegMsg[] = { " has no physreg",
  2251. " defines a physreg" };
  2252. #endif
  2253. LLVM_DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
  2254. << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum
  2255. << ") " << PhysRegMsg[RHasPhysReg] << "\n");
  2256. return LHasPhysReg < RHasPhysReg;
  2257. }
  2258. }
  2259. // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
  2260. unsigned LPriority = SPQ->getNodePriority(left);
  2261. unsigned RPriority = SPQ->getNodePriority(right);
  2262. // Be really careful about hoisting call operands above previous calls.
  2263. // Only allows it if it would reduce register pressure.
  2264. if (left->isCall && right->isCallOp) {
  2265. unsigned RNumVals = right->getNode()->getNumValues();
  2266. RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
  2267. }
  2268. if (right->isCall && left->isCallOp) {
  2269. unsigned LNumVals = left->getNode()->getNumValues();
  2270. LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
  2271. }
  2272. if (LPriority != RPriority)
  2273. return LPriority > RPriority;
  2274. // One or both of the nodes are calls and their sethi-ullman numbers are the
  2275. // same, then keep source order.
  2276. if (left->isCall || right->isCall) {
  2277. unsigned LOrder = SPQ->getNodeOrdering(left);
  2278. unsigned ROrder = SPQ->getNodeOrdering(right);
  2279. // Prefer an ordering where the lower the non-zero order number, the higher
  2280. // the preference.
  2281. if ((LOrder || ROrder) && LOrder != ROrder)
  2282. return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
  2283. }
  2284. // Try schedule def + use closer when Sethi-Ullman numbers are the same.
  2285. // e.g.
  2286. // t1 = op t2, c1
  2287. // t3 = op t4, c2
  2288. //
  2289. // and the following instructions are both ready.
  2290. // t2 = op c3
  2291. // t4 = op c4
  2292. //
  2293. // Then schedule t2 = op first.
  2294. // i.e.
  2295. // t4 = op c4
  2296. // t2 = op c3
  2297. // t1 = op t2, c1
  2298. // t3 = op t4, c2
  2299. //
  2300. // This creates more short live intervals.
  2301. unsigned LDist = closestSucc(left);
  2302. unsigned RDist = closestSucc(right);
  2303. if (LDist != RDist)
  2304. return LDist < RDist;
  2305. // How many registers becomes live when the node is scheduled.
  2306. unsigned LScratch = calcMaxScratches(left);
  2307. unsigned RScratch = calcMaxScratches(right);
  2308. if (LScratch != RScratch)
  2309. return LScratch > RScratch;
  2310. // Comparing latency against a call makes little sense unless the node
  2311. // is register pressure-neutral.
  2312. if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
  2313. return (left->NodeQueueId > right->NodeQueueId);
  2314. // Do not compare latencies when one or both of the nodes are calls.
  2315. if (!DisableSchedCycles &&
  2316. !(left->isCall || right->isCall)) {
  2317. int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
  2318. if (result != 0)
  2319. return result > 0;
  2320. }
  2321. else {
  2322. if (left->getHeight() != right->getHeight())
  2323. return left->getHeight() > right->getHeight();
  2324. if (left->getDepth() != right->getDepth())
  2325. return left->getDepth() < right->getDepth();
  2326. }
  2327. assert(left->NodeQueueId && right->NodeQueueId &&
  2328. "NodeQueueId cannot be zero");
  2329. return (left->NodeQueueId > right->NodeQueueId);
  2330. }
  2331. // Bottom up
  2332. bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2333. if (int res = checkSpecialNodes(left, right))
  2334. return res > 0;
  2335. return BURRSort(left, right, SPQ);
  2336. }
  2337. // Source order, otherwise bottom up.
  2338. bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2339. if (int res = checkSpecialNodes(left, right))
  2340. return res > 0;
  2341. unsigned LOrder = SPQ->getNodeOrdering(left);
  2342. unsigned ROrder = SPQ->getNodeOrdering(right);
  2343. // Prefer an ordering where the lower the non-zero order number, the higher
  2344. // the preference.
  2345. if ((LOrder || ROrder) && LOrder != ROrder)
  2346. return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
  2347. return BURRSort(left, right, SPQ);
  2348. }
  2349. // If the time between now and when the instruction will be ready can cover
  2350. // the spill code, then avoid adding it to the ready queue. This gives long
  2351. // stalls highest priority and allows hoisting across calls. It should also
  2352. // speed up processing the available queue.
  2353. bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
  2354. static const unsigned ReadyDelay = 3;
  2355. if (SPQ->MayReduceRegPressure(SU)) return true;
  2356. if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
  2357. if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
  2358. != ScheduleHazardRecognizer::NoHazard)
  2359. return false;
  2360. return true;
  2361. }
  2362. // Return true if right should be scheduled with higher priority than left.
  2363. bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2364. if (int res = checkSpecialNodes(left, right))
  2365. return res > 0;
  2366. if (left->isCall || right->isCall)
  2367. // No way to compute latency of calls.
  2368. return BURRSort(left, right, SPQ);
  2369. bool LHigh = SPQ->HighRegPressure(left);
  2370. bool RHigh = SPQ->HighRegPressure(right);
  2371. // Avoid causing spills. If register pressure is high, schedule for
  2372. // register pressure reduction.
  2373. if (LHigh && !RHigh) {
  2374. LLVM_DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
  2375. << right->NodeNum << ")\n");
  2376. return true;
  2377. }
  2378. else if (!LHigh && RHigh) {
  2379. LLVM_DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
  2380. << left->NodeNum << ")\n");
  2381. return false;
  2382. }
  2383. if (!LHigh && !RHigh) {
  2384. int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
  2385. if (result != 0)
  2386. return result > 0;
  2387. }
  2388. return BURRSort(left, right, SPQ);
  2389. }
  2390. // Schedule as many instructions in each cycle as possible. So don't make an
  2391. // instruction available unless it is ready in the current cycle.
  2392. bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
  2393. if (SU->getHeight() > CurCycle) return false;
  2394. if (SPQ->getHazardRec()->getHazardType(SU, 0)
  2395. != ScheduleHazardRecognizer::NoHazard)
  2396. return false;
  2397. return true;
  2398. }
  2399. static bool canEnableCoalescing(SUnit *SU) {
  2400. unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
  2401. if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
  2402. // CopyToReg should be close to its uses to facilitate coalescing and
  2403. // avoid spilling.
  2404. return true;
  2405. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  2406. Opc == TargetOpcode::SUBREG_TO_REG ||
  2407. Opc == TargetOpcode::INSERT_SUBREG)
  2408. // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
  2409. // close to their uses to facilitate coalescing.
  2410. return true;
  2411. if (SU->NumPreds == 0 && SU->NumSuccs != 0)
  2412. // If SU does not have a register def, schedule it close to its uses
  2413. // because it does not lengthen any live ranges.
  2414. return true;
  2415. return false;
  2416. }
  2417. // list-ilp is currently an experimental scheduler that allows various
  2418. // heuristics to be enabled prior to the normal register reduction logic.
  2419. bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
  2420. if (int res = checkSpecialNodes(left, right))
  2421. return res > 0;
  2422. if (left->isCall || right->isCall)
  2423. // No way to compute latency of calls.
  2424. return BURRSort(left, right, SPQ);
  2425. unsigned LLiveUses = 0, RLiveUses = 0;
  2426. int LPDiff = 0, RPDiff = 0;
  2427. if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
  2428. LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
  2429. RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
  2430. }
  2431. if (!DisableSchedRegPressure && LPDiff != RPDiff) {
  2432. LLVM_DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum
  2433. << "): " << LPDiff << " != SU(" << right->NodeNum
  2434. << "): " << RPDiff << "\n");
  2435. return LPDiff > RPDiff;
  2436. }
  2437. if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
  2438. bool LReduce = canEnableCoalescing(left);
  2439. bool RReduce = canEnableCoalescing(right);
  2440. if (LReduce && !RReduce) return false;
  2441. if (RReduce && !LReduce) return true;
  2442. }
  2443. if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
  2444. LLVM_DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
  2445. << " != SU(" << right->NodeNum << "): " << RLiveUses
  2446. << "\n");
  2447. return LLiveUses < RLiveUses;
  2448. }
  2449. if (!DisableSchedStalls) {
  2450. bool LStall = BUHasStall(left, left->getHeight(), SPQ);
  2451. bool RStall = BUHasStall(right, right->getHeight(), SPQ);
  2452. if (LStall != RStall)
  2453. return left->getHeight() > right->getHeight();
  2454. }
  2455. if (!DisableSchedCriticalPath) {
  2456. int spread = (int)left->getDepth() - (int)right->getDepth();
  2457. if (std::abs(spread) > MaxReorderWindow) {
  2458. LLVM_DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
  2459. << left->getDepth() << " != SU(" << right->NodeNum
  2460. << "): " << right->getDepth() << "\n");
  2461. return left->getDepth() < right->getDepth();
  2462. }
  2463. }
  2464. if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
  2465. int spread = (int)left->getHeight() - (int)right->getHeight();
  2466. if (std::abs(spread) > MaxReorderWindow)
  2467. return left->getHeight() > right->getHeight();
  2468. }
  2469. return BURRSort(left, right, SPQ);
  2470. }
  2471. void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
  2472. SUnits = &sunits;
  2473. // Add pseudo dependency edges for two-address nodes.
  2474. if (!Disable2AddrHack)
  2475. AddPseudoTwoAddrDeps();
  2476. // Reroute edges to nodes with multiple uses.
  2477. if (!TracksRegPressure && !SrcOrder)
  2478. PrescheduleNodesWithMultipleUses();
  2479. // Calculate node priorities.
  2480. CalculateSethiUllmanNumbers();
  2481. // For single block loops, mark nodes that look like canonical IV increments.
  2482. if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB))
  2483. for (SUnit &SU : sunits)
  2484. initVRegCycle(&SU);
  2485. }
  2486. //===----------------------------------------------------------------------===//
  2487. // Preschedule for Register Pressure
  2488. //===----------------------------------------------------------------------===//
  2489. bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
  2490. if (SU->isTwoAddress) {
  2491. unsigned Opc = SU->getNode()->getMachineOpcode();
  2492. const MCInstrDesc &MCID = TII->get(Opc);
  2493. unsigned NumRes = MCID.getNumDefs();
  2494. unsigned NumOps = MCID.getNumOperands() - NumRes;
  2495. for (unsigned i = 0; i != NumOps; ++i) {
  2496. if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
  2497. SDNode *DU = SU->getNode()->getOperand(i).getNode();
  2498. if (DU->getNodeId() != -1 &&
  2499. Op->OrigNode == &(*SUnits)[DU->getNodeId()])
  2500. return true;
  2501. }
  2502. }
  2503. }
  2504. return false;
  2505. }
  2506. /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
  2507. /// successor's explicit physregs whose definition can reach DepSU.
  2508. /// i.e. DepSU should not be scheduled above SU.
  2509. static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
  2510. ScheduleDAGRRList *scheduleDAG,
  2511. const TargetInstrInfo *TII,
  2512. const TargetRegisterInfo *TRI) {
  2513. ArrayRef<MCPhysReg> ImpDefs =
  2514. TII->get(SU->getNode()->getMachineOpcode()).implicit_defs();
  2515. const uint32_t *RegMask = getNodeRegMask(SU->getNode());
  2516. if (ImpDefs.empty() && !RegMask)
  2517. return false;
  2518. for (const SDep &Succ : SU->Succs) {
  2519. SUnit *SuccSU = Succ.getSUnit();
  2520. for (const SDep &SuccPred : SuccSU->Preds) {
  2521. if (!SuccPred.isAssignedRegDep())
  2522. continue;
  2523. if (RegMask &&
  2524. MachineOperand::clobbersPhysReg(RegMask, SuccPred.getReg()) &&
  2525. scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
  2526. return true;
  2527. for (MCPhysReg ImpDef : ImpDefs) {
  2528. // Return true if SU clobbers this physical register use and the
  2529. // definition of the register reaches from DepSU. IsReachable queries
  2530. // a topological forward sort of the DAG (following the successors).
  2531. if (TRI->regsOverlap(ImpDef, SuccPred.getReg()) &&
  2532. scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
  2533. return true;
  2534. }
  2535. }
  2536. }
  2537. return false;
  2538. }
  2539. /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
  2540. /// physical register defs.
  2541. static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
  2542. const TargetInstrInfo *TII,
  2543. const TargetRegisterInfo *TRI) {
  2544. SDNode *N = SuccSU->getNode();
  2545. unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
  2546. ArrayRef<MCPhysReg> ImpDefs = TII->get(N->getMachineOpcode()).implicit_defs();
  2547. assert(!ImpDefs.empty() && "Caller should check hasPhysRegDefs");
  2548. for (const SDNode *SUNode = SU->getNode(); SUNode;
  2549. SUNode = SUNode->getGluedNode()) {
  2550. if (!SUNode->isMachineOpcode())
  2551. continue;
  2552. ArrayRef<MCPhysReg> SUImpDefs =
  2553. TII->get(SUNode->getMachineOpcode()).implicit_defs();
  2554. const uint32_t *SURegMask = getNodeRegMask(SUNode);
  2555. if (SUImpDefs.empty() && !SURegMask)
  2556. continue;
  2557. for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
  2558. MVT VT = N->getSimpleValueType(i);
  2559. if (VT == MVT::Glue || VT == MVT::Other)
  2560. continue;
  2561. if (!N->hasAnyUseOfValue(i))
  2562. continue;
  2563. MCPhysReg Reg = ImpDefs[i - NumDefs];
  2564. if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
  2565. return true;
  2566. for (MCPhysReg SUReg : SUImpDefs) {
  2567. if (TRI->regsOverlap(Reg, SUReg))
  2568. return true;
  2569. }
  2570. }
  2571. }
  2572. return false;
  2573. }
  2574. /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
  2575. /// are not handled well by the general register pressure reduction
  2576. /// heuristics. When presented with code like this:
  2577. ///
  2578. /// N
  2579. /// / |
  2580. /// / |
  2581. /// U store
  2582. /// |
  2583. /// ...
  2584. ///
  2585. /// the heuristics tend to push the store up, but since the
  2586. /// operand of the store has another use (U), this would increase
  2587. /// the length of that other use (the U->N edge).
  2588. ///
  2589. /// This function transforms code like the above to route U's
  2590. /// dependence through the store when possible, like this:
  2591. ///
  2592. /// N
  2593. /// ||
  2594. /// ||
  2595. /// store
  2596. /// |
  2597. /// U
  2598. /// |
  2599. /// ...
  2600. ///
  2601. /// This results in the store being scheduled immediately
  2602. /// after N, which shortens the U->N live range, reducing
  2603. /// register pressure.
  2604. void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
  2605. // Visit all the nodes in topological order, working top-down.
  2606. for (SUnit &SU : *SUnits) {
  2607. // For now, only look at nodes with no data successors, such as stores.
  2608. // These are especially important, due to the heuristics in
  2609. // getNodePriority for nodes with no data successors.
  2610. if (SU.NumSuccs != 0)
  2611. continue;
  2612. // For now, only look at nodes with exactly one data predecessor.
  2613. if (SU.NumPreds != 1)
  2614. continue;
  2615. // Avoid prescheduling copies to virtual registers, which don't behave
  2616. // like other nodes from the perspective of scheduling heuristics.
  2617. if (SDNode *N = SU.getNode())
  2618. if (N->getOpcode() == ISD::CopyToReg &&
  2619. cast<RegisterSDNode>(N->getOperand(1))->getReg().isVirtual())
  2620. continue;
  2621. SDNode *PredFrameSetup = nullptr;
  2622. for (const SDep &Pred : SU.Preds)
  2623. if (Pred.isCtrl() && Pred.getSUnit()) {
  2624. // Find the predecessor which is not data dependence.
  2625. SDNode *PredND = Pred.getSUnit()->getNode();
  2626. // If PredND is FrameSetup, we should not pre-scheduled the node,
  2627. // or else, when bottom up scheduling, ADJCALLSTACKDOWN and
  2628. // ADJCALLSTACKUP may hold CallResource too long and make other
  2629. // calls can't be scheduled. If there's no other available node
  2630. // to schedule, the schedular will try to rename the register by
  2631. // creating copy to avoid the conflict which will fail because
  2632. // CallResource is not a real physical register.
  2633. if (PredND && PredND->isMachineOpcode() &&
  2634. (PredND->getMachineOpcode() == TII->getCallFrameSetupOpcode())) {
  2635. PredFrameSetup = PredND;
  2636. break;
  2637. }
  2638. }
  2639. // Skip the node has FrameSetup parent.
  2640. if (PredFrameSetup != nullptr)
  2641. continue;
  2642. // Locate the single data predecessor.
  2643. SUnit *PredSU = nullptr;
  2644. for (const SDep &Pred : SU.Preds)
  2645. if (!Pred.isCtrl()) {
  2646. PredSU = Pred.getSUnit();
  2647. break;
  2648. }
  2649. assert(PredSU);
  2650. // Don't rewrite edges that carry physregs, because that requires additional
  2651. // support infrastructure.
  2652. if (PredSU->hasPhysRegDefs)
  2653. continue;
  2654. // Short-circuit the case where SU is PredSU's only data successor.
  2655. if (PredSU->NumSuccs == 1)
  2656. continue;
  2657. // Avoid prescheduling to copies from virtual registers, which don't behave
  2658. // like other nodes from the perspective of scheduling heuristics.
  2659. if (SDNode *N = SU.getNode())
  2660. if (N->getOpcode() == ISD::CopyFromReg &&
  2661. cast<RegisterSDNode>(N->getOperand(1))->getReg().isVirtual())
  2662. continue;
  2663. // Perform checks on the successors of PredSU.
  2664. for (const SDep &PredSucc : PredSU->Succs) {
  2665. SUnit *PredSuccSU = PredSucc.getSUnit();
  2666. if (PredSuccSU == &SU) continue;
  2667. // If PredSU has another successor with no data successors, for
  2668. // now don't attempt to choose either over the other.
  2669. if (PredSuccSU->NumSuccs == 0)
  2670. goto outer_loop_continue;
  2671. // Don't break physical register dependencies.
  2672. if (SU.hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
  2673. if (canClobberPhysRegDefs(PredSuccSU, &SU, TII, TRI))
  2674. goto outer_loop_continue;
  2675. // Don't introduce graph cycles.
  2676. if (scheduleDAG->IsReachable(&SU, PredSuccSU))
  2677. goto outer_loop_continue;
  2678. }
  2679. // Ok, the transformation is safe and the heuristics suggest it is
  2680. // profitable. Update the graph.
  2681. LLVM_DEBUG(
  2682. dbgs() << " Prescheduling SU #" << SU.NodeNum << " next to PredSU #"
  2683. << PredSU->NodeNum
  2684. << " to guide scheduling in the presence of multiple uses\n");
  2685. for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
  2686. SDep Edge = PredSU->Succs[i];
  2687. assert(!Edge.isAssignedRegDep());
  2688. SUnit *SuccSU = Edge.getSUnit();
  2689. if (SuccSU != &SU) {
  2690. Edge.setSUnit(PredSU);
  2691. scheduleDAG->RemovePred(SuccSU, Edge);
  2692. scheduleDAG->AddPredQueued(&SU, Edge);
  2693. Edge.setSUnit(&SU);
  2694. scheduleDAG->AddPredQueued(SuccSU, Edge);
  2695. --i;
  2696. }
  2697. }
  2698. outer_loop_continue:;
  2699. }
  2700. }
  2701. /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
  2702. /// it as a def&use operand. Add a pseudo control edge from it to the other
  2703. /// node (if it won't create a cycle) so the two-address one will be scheduled
  2704. /// first (lower in the schedule). If both nodes are two-address, favor the
  2705. /// one that has a CopyToReg use (more likely to be a loop induction update).
  2706. /// If both are two-address, but one is commutable while the other is not
  2707. /// commutable, favor the one that's not commutable.
  2708. void RegReductionPQBase::AddPseudoTwoAddrDeps() {
  2709. for (SUnit &SU : *SUnits) {
  2710. if (!SU.isTwoAddress)
  2711. continue;
  2712. SDNode *Node = SU.getNode();
  2713. if (!Node || !Node->isMachineOpcode() || SU.getNode()->getGluedNode())
  2714. continue;
  2715. bool isLiveOut = hasOnlyLiveOutUses(&SU);
  2716. unsigned Opc = Node->getMachineOpcode();
  2717. const MCInstrDesc &MCID = TII->get(Opc);
  2718. unsigned NumRes = MCID.getNumDefs();
  2719. unsigned NumOps = MCID.getNumOperands() - NumRes;
  2720. for (unsigned j = 0; j != NumOps; ++j) {
  2721. if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
  2722. continue;
  2723. SDNode *DU = SU.getNode()->getOperand(j).getNode();
  2724. if (DU->getNodeId() == -1)
  2725. continue;
  2726. const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
  2727. if (!DUSU)
  2728. continue;
  2729. for (const SDep &Succ : DUSU->Succs) {
  2730. if (Succ.isCtrl())
  2731. continue;
  2732. SUnit *SuccSU = Succ.getSUnit();
  2733. if (SuccSU == &SU)
  2734. continue;
  2735. // Be conservative. Ignore if nodes aren't at roughly the same
  2736. // depth and height.
  2737. if (SuccSU->getHeight() < SU.getHeight() &&
  2738. (SU.getHeight() - SuccSU->getHeight()) > 1)
  2739. continue;
  2740. // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
  2741. // constrains whatever is using the copy, instead of the copy
  2742. // itself. In the case that the copy is coalesced, this
  2743. // preserves the intent of the pseudo two-address heurietics.
  2744. while (SuccSU->Succs.size() == 1 &&
  2745. SuccSU->getNode()->isMachineOpcode() &&
  2746. SuccSU->getNode()->getMachineOpcode() ==
  2747. TargetOpcode::COPY_TO_REGCLASS)
  2748. SuccSU = SuccSU->Succs.front().getSUnit();
  2749. // Don't constrain non-instruction nodes.
  2750. if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
  2751. continue;
  2752. // Don't constrain nodes with physical register defs if the
  2753. // predecessor can clobber them.
  2754. if (SuccSU->hasPhysRegDefs && SU.hasPhysRegClobbers) {
  2755. if (canClobberPhysRegDefs(SuccSU, &SU, TII, TRI))
  2756. continue;
  2757. }
  2758. // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
  2759. // these may be coalesced away. We want them close to their uses.
  2760. unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
  2761. if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
  2762. SuccOpc == TargetOpcode::INSERT_SUBREG ||
  2763. SuccOpc == TargetOpcode::SUBREG_TO_REG)
  2764. continue;
  2765. if (!canClobberReachingPhysRegUse(SuccSU, &SU, scheduleDAG, TII, TRI) &&
  2766. (!canClobber(SuccSU, DUSU) ||
  2767. (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
  2768. (!SU.isCommutable && SuccSU->isCommutable)) &&
  2769. !scheduleDAG->IsReachable(SuccSU, &SU)) {
  2770. LLVM_DEBUG(dbgs()
  2771. << " Adding a pseudo-two-addr edge from SU #"
  2772. << SU.NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
  2773. scheduleDAG->AddPredQueued(&SU, SDep(SuccSU, SDep::Artificial));
  2774. }
  2775. }
  2776. }
  2777. }
  2778. }
  2779. //===----------------------------------------------------------------------===//
  2780. // Public Constructor Functions
  2781. //===----------------------------------------------------------------------===//
  2782. ScheduleDAGSDNodes *
  2783. llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
  2784. CodeGenOpt::Level OptLevel) {
  2785. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2786. const TargetInstrInfo *TII = STI.getInstrInfo();
  2787. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2788. BURegReductionPriorityQueue *PQ =
  2789. new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
  2790. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
  2791. PQ->setScheduleDAG(SD);
  2792. return SD;
  2793. }
  2794. ScheduleDAGSDNodes *
  2795. llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
  2796. CodeGenOpt::Level OptLevel) {
  2797. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2798. const TargetInstrInfo *TII = STI.getInstrInfo();
  2799. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2800. SrcRegReductionPriorityQueue *PQ =
  2801. new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
  2802. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
  2803. PQ->setScheduleDAG(SD);
  2804. return SD;
  2805. }
  2806. ScheduleDAGSDNodes *
  2807. llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
  2808. CodeGenOpt::Level OptLevel) {
  2809. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2810. const TargetInstrInfo *TII = STI.getInstrInfo();
  2811. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2812. const TargetLowering *TLI = IS->TLI;
  2813. HybridBURRPriorityQueue *PQ =
  2814. new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
  2815. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
  2816. PQ->setScheduleDAG(SD);
  2817. return SD;
  2818. }
  2819. ScheduleDAGSDNodes *
  2820. llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
  2821. CodeGenOpt::Level OptLevel) {
  2822. const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
  2823. const TargetInstrInfo *TII = STI.getInstrInfo();
  2824. const TargetRegisterInfo *TRI = STI.getRegisterInfo();
  2825. const TargetLowering *TLI = IS->TLI;
  2826. ILPBURRPriorityQueue *PQ =
  2827. new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
  2828. ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
  2829. PQ->setScheduleDAG(SD);
  2830. return SD;
  2831. }