MachinePipeliner.cpp 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028
  1. //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
  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. // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
  10. //
  11. // This SMS implementation is a target-independent back-end pass. When enabled,
  12. // the pass runs just prior to the register allocation pass, while the machine
  13. // IR is in SSA form. If software pipelining is successful, then the original
  14. // loop is replaced by the optimized loop. The optimized loop contains one or
  15. // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
  16. // the instructions cannot be scheduled in a given MII, we increase the MII by
  17. // one and try again.
  18. //
  19. // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
  20. // represent loop carried dependences in the DAG as order edges to the Phi
  21. // nodes. We also perform several passes over the DAG to eliminate unnecessary
  22. // edges that inhibit the ability to pipeline. The implementation uses the
  23. // DFAPacketizer class to compute the minimum initiation interval and the check
  24. // where an instruction may be inserted in the pipelined schedule.
  25. //
  26. // In order for the SMS pass to work, several target specific hooks need to be
  27. // implemented to get information about the loop structure and to rewrite
  28. // instructions.
  29. //
  30. //===----------------------------------------------------------------------===//
  31. #include "llvm/ADT/ArrayRef.h"
  32. #include "llvm/ADT/BitVector.h"
  33. #include "llvm/ADT/DenseMap.h"
  34. #include "llvm/ADT/MapVector.h"
  35. #include "llvm/ADT/PriorityQueue.h"
  36. #include "llvm/ADT/SetVector.h"
  37. #include "llvm/ADT/SmallPtrSet.h"
  38. #include "llvm/ADT/SmallSet.h"
  39. #include "llvm/ADT/SmallVector.h"
  40. #include "llvm/ADT/Statistic.h"
  41. #include "llvm/ADT/iterator_range.h"
  42. #include "llvm/Analysis/AliasAnalysis.h"
  43. #include "llvm/Analysis/MemoryLocation.h"
  44. #include "llvm/Analysis/ValueTracking.h"
  45. #include "llvm/CodeGen/DFAPacketizer.h"
  46. #include "llvm/CodeGen/LiveIntervals.h"
  47. #include "llvm/CodeGen/MachineBasicBlock.h"
  48. #include "llvm/CodeGen/MachineDominators.h"
  49. #include "llvm/CodeGen/MachineFunction.h"
  50. #include "llvm/CodeGen/MachineFunctionPass.h"
  51. #include "llvm/CodeGen/MachineInstr.h"
  52. #include "llvm/CodeGen/MachineInstrBuilder.h"
  53. #include "llvm/CodeGen/MachineLoopInfo.h"
  54. #include "llvm/CodeGen/MachineMemOperand.h"
  55. #include "llvm/CodeGen/MachineOperand.h"
  56. #include "llvm/CodeGen/MachinePipeliner.h"
  57. #include "llvm/CodeGen/MachineRegisterInfo.h"
  58. #include "llvm/CodeGen/ModuloSchedule.h"
  59. #include "llvm/CodeGen/RegisterPressure.h"
  60. #include "llvm/CodeGen/ScheduleDAG.h"
  61. #include "llvm/CodeGen/ScheduleDAGMutation.h"
  62. #include "llvm/CodeGen/TargetOpcodes.h"
  63. #include "llvm/CodeGen/TargetRegisterInfo.h"
  64. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  65. #include "llvm/Config/llvm-config.h"
  66. #include "llvm/IR/Attributes.h"
  67. #include "llvm/IR/DebugLoc.h"
  68. #include "llvm/IR/Function.h"
  69. #include "llvm/MC/LaneBitmask.h"
  70. #include "llvm/MC/MCInstrDesc.h"
  71. #include "llvm/MC/MCInstrItineraries.h"
  72. #include "llvm/MC/MCRegisterInfo.h"
  73. #include "llvm/Pass.h"
  74. #include "llvm/Support/CommandLine.h"
  75. #include "llvm/Support/Compiler.h"
  76. #include "llvm/Support/Debug.h"
  77. #include "llvm/Support/MathExtras.h"
  78. #include "llvm/Support/raw_ostream.h"
  79. #include <algorithm>
  80. #include <cassert>
  81. #include <climits>
  82. #include <cstdint>
  83. #include <deque>
  84. #include <functional>
  85. #include <iterator>
  86. #include <map>
  87. #include <memory>
  88. #include <tuple>
  89. #include <utility>
  90. #include <vector>
  91. using namespace llvm;
  92. #define DEBUG_TYPE "pipeliner"
  93. STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
  94. STATISTIC(NumPipelined, "Number of loops software pipelined");
  95. STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
  96. STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
  97. STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
  98. STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
  99. STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
  100. STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
  101. STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
  102. STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
  103. STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
  104. /// A command line option to turn software pipelining on or off.
  105. static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
  106. cl::ZeroOrMore,
  107. cl::desc("Enable Software Pipelining"));
  108. /// A command line option to enable SWP at -Os.
  109. static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
  110. cl::desc("Enable SWP at Os."), cl::Hidden,
  111. cl::init(false));
  112. /// A command line argument to limit minimum initial interval for pipelining.
  113. static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
  114. cl::desc("Size limit for the MII."),
  115. cl::Hidden, cl::init(27));
  116. /// A command line argument to limit the number of stages in the pipeline.
  117. static cl::opt<int>
  118. SwpMaxStages("pipeliner-max-stages",
  119. cl::desc("Maximum stages allowed in the generated scheduled."),
  120. cl::Hidden, cl::init(3));
  121. /// A command line option to disable the pruning of chain dependences due to
  122. /// an unrelated Phi.
  123. static cl::opt<bool>
  124. SwpPruneDeps("pipeliner-prune-deps",
  125. cl::desc("Prune dependences between unrelated Phi nodes."),
  126. cl::Hidden, cl::init(true));
  127. /// A command line option to disable the pruning of loop carried order
  128. /// dependences.
  129. static cl::opt<bool>
  130. SwpPruneLoopCarried("pipeliner-prune-loop-carried",
  131. cl::desc("Prune loop carried order dependences."),
  132. cl::Hidden, cl::init(true));
  133. #ifndef NDEBUG
  134. static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
  135. #endif
  136. static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
  137. cl::ReallyHidden, cl::init(false),
  138. cl::ZeroOrMore, cl::desc("Ignore RecMII"));
  139. static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
  140. cl::init(false));
  141. static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
  142. cl::init(false));
  143. static cl::opt<bool> EmitTestAnnotations(
  144. "pipeliner-annotate-for-testing", cl::Hidden, cl::init(false),
  145. cl::desc("Instead of emitting the pipelined code, annotate instructions "
  146. "with the generated schedule for feeding into the "
  147. "-modulo-schedule-test pass"));
  148. static cl::opt<bool> ExperimentalCodeGen(
  149. "pipeliner-experimental-cg", cl::Hidden, cl::init(false),
  150. cl::desc(
  151. "Use the experimental peeling code generator for software pipelining"));
  152. namespace llvm {
  153. // A command line option to enable the CopyToPhi DAG mutation.
  154. cl::opt<bool>
  155. SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
  156. cl::init(true), cl::ZeroOrMore,
  157. cl::desc("Enable CopyToPhi DAG Mutation"));
  158. } // end namespace llvm
  159. unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
  160. char MachinePipeliner::ID = 0;
  161. #ifndef NDEBUG
  162. int MachinePipeliner::NumTries = 0;
  163. #endif
  164. char &llvm::MachinePipelinerID = MachinePipeliner::ID;
  165. INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
  166. "Modulo Software Pipelining", false, false)
  167. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  168. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  169. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  170. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  171. INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
  172. "Modulo Software Pipelining", false, false)
  173. /// The "main" function for implementing Swing Modulo Scheduling.
  174. bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
  175. if (skipFunction(mf.getFunction()))
  176. return false;
  177. if (!EnableSWP)
  178. return false;
  179. if (mf.getFunction().getAttributes().hasAttribute(
  180. AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
  181. !EnableSWPOptSize.getPosition())
  182. return false;
  183. if (!mf.getSubtarget().enableMachinePipeliner())
  184. return false;
  185. // Cannot pipeline loops without instruction itineraries if we are using
  186. // DFA for the pipeliner.
  187. if (mf.getSubtarget().useDFAforSMS() &&
  188. (!mf.getSubtarget().getInstrItineraryData() ||
  189. mf.getSubtarget().getInstrItineraryData()->isEmpty()))
  190. return false;
  191. MF = &mf;
  192. MLI = &getAnalysis<MachineLoopInfo>();
  193. MDT = &getAnalysis<MachineDominatorTree>();
  194. TII = MF->getSubtarget().getInstrInfo();
  195. RegClassInfo.runOnMachineFunction(*MF);
  196. for (auto &L : *MLI)
  197. scheduleLoop(*L);
  198. return false;
  199. }
  200. /// Attempt to perform the SMS algorithm on the specified loop. This function is
  201. /// the main entry point for the algorithm. The function identifies candidate
  202. /// loops, calculates the minimum initiation interval, and attempts to schedule
  203. /// the loop.
  204. bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
  205. bool Changed = false;
  206. for (auto &InnerLoop : L)
  207. Changed |= scheduleLoop(*InnerLoop);
  208. #ifndef NDEBUG
  209. // Stop trying after reaching the limit (if any).
  210. int Limit = SwpLoopLimit;
  211. if (Limit >= 0) {
  212. if (NumTries >= SwpLoopLimit)
  213. return Changed;
  214. NumTries++;
  215. }
  216. #endif
  217. setPragmaPipelineOptions(L);
  218. if (!canPipelineLoop(L)) {
  219. LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
  220. return Changed;
  221. }
  222. ++NumTrytoPipeline;
  223. Changed = swingModuloScheduler(L);
  224. return Changed;
  225. }
  226. void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
  227. MachineBasicBlock *LBLK = L.getTopBlock();
  228. if (LBLK == nullptr)
  229. return;
  230. const BasicBlock *BBLK = LBLK->getBasicBlock();
  231. if (BBLK == nullptr)
  232. return;
  233. const Instruction *TI = BBLK->getTerminator();
  234. if (TI == nullptr)
  235. return;
  236. MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
  237. if (LoopID == nullptr)
  238. return;
  239. assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
  240. assert(LoopID->getOperand(0) == LoopID && "invalid loop");
  241. for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
  242. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  243. if (MD == nullptr)
  244. continue;
  245. MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  246. if (S == nullptr)
  247. continue;
  248. if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
  249. assert(MD->getNumOperands() == 2 &&
  250. "Pipeline initiation interval hint metadata should have two operands.");
  251. II_setByPragma =
  252. mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
  253. assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
  254. } else if (S->getString() == "llvm.loop.pipeline.disable") {
  255. disabledByPragma = true;
  256. }
  257. }
  258. }
  259. /// Return true if the loop can be software pipelined. The algorithm is
  260. /// restricted to loops with a single basic block. Make sure that the
  261. /// branch in the loop can be analyzed.
  262. bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
  263. if (L.getNumBlocks() != 1)
  264. return false;
  265. if (disabledByPragma)
  266. return false;
  267. // Check if the branch can't be understood because we can't do pipelining
  268. // if that's the case.
  269. LI.TBB = nullptr;
  270. LI.FBB = nullptr;
  271. LI.BrCond.clear();
  272. if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
  273. LLVM_DEBUG(
  274. dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n");
  275. NumFailBranch++;
  276. return false;
  277. }
  278. LI.LoopInductionVar = nullptr;
  279. LI.LoopCompare = nullptr;
  280. if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare)) {
  281. LLVM_DEBUG(
  282. dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n");
  283. NumFailLoop++;
  284. return false;
  285. }
  286. if (!L.getLoopPreheader()) {
  287. LLVM_DEBUG(
  288. dbgs() << "Preheader not found, can NOT pipeline current Loop\n");
  289. NumFailPreheader++;
  290. return false;
  291. }
  292. // Remove any subregisters from inputs to phi nodes.
  293. preprocessPhiNodes(*L.getHeader());
  294. return true;
  295. }
  296. void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
  297. MachineRegisterInfo &MRI = MF->getRegInfo();
  298. SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
  299. for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
  300. MachineOperand &DefOp = PI.getOperand(0);
  301. assert(DefOp.getSubReg() == 0);
  302. auto *RC = MRI.getRegClass(DefOp.getReg());
  303. for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
  304. MachineOperand &RegOp = PI.getOperand(i);
  305. if (RegOp.getSubReg() == 0)
  306. continue;
  307. // If the operand uses a subregister, replace it with a new register
  308. // without subregisters, and generate a copy to the new register.
  309. Register NewReg = MRI.createVirtualRegister(RC);
  310. MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
  311. MachineBasicBlock::iterator At = PredB.getFirstTerminator();
  312. const DebugLoc &DL = PredB.findDebugLoc(At);
  313. auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
  314. .addReg(RegOp.getReg(), getRegState(RegOp),
  315. RegOp.getSubReg());
  316. Slots.insertMachineInstrInMaps(*Copy);
  317. RegOp.setReg(NewReg);
  318. RegOp.setSubReg(0);
  319. }
  320. }
  321. }
  322. /// The SMS algorithm consists of the following main steps:
  323. /// 1. Computation and analysis of the dependence graph.
  324. /// 2. Ordering of the nodes (instructions).
  325. /// 3. Attempt to Schedule the loop.
  326. bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
  327. assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
  328. SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
  329. II_setByPragma);
  330. MachineBasicBlock *MBB = L.getHeader();
  331. // The kernel should not include any terminator instructions. These
  332. // will be added back later.
  333. SMS.startBlock(MBB);
  334. // Compute the number of 'real' instructions in the basic block by
  335. // ignoring terminators.
  336. unsigned size = MBB->size();
  337. for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
  338. E = MBB->instr_end();
  339. I != E; ++I, --size)
  340. ;
  341. SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
  342. SMS.schedule();
  343. SMS.exitRegion();
  344. SMS.finishBlock();
  345. return SMS.hasNewSchedule();
  346. }
  347. void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
  348. if (II_setByPragma > 0)
  349. MII = II_setByPragma;
  350. else
  351. MII = std::max(ResMII, RecMII);
  352. }
  353. void SwingSchedulerDAG::setMAX_II() {
  354. if (II_setByPragma > 0)
  355. MAX_II = II_setByPragma;
  356. else
  357. MAX_II = MII + 10;
  358. }
  359. /// We override the schedule function in ScheduleDAGInstrs to implement the
  360. /// scheduling part of the Swing Modulo Scheduling algorithm.
  361. void SwingSchedulerDAG::schedule() {
  362. AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
  363. buildSchedGraph(AA);
  364. addLoopCarriedDependences(AA);
  365. updatePhiDependences();
  366. Topo.InitDAGTopologicalSorting();
  367. changeDependences();
  368. postprocessDAG();
  369. LLVM_DEBUG(dump());
  370. NodeSetType NodeSets;
  371. findCircuits(NodeSets);
  372. NodeSetType Circuits = NodeSets;
  373. // Calculate the MII.
  374. unsigned ResMII = calculateResMII();
  375. unsigned RecMII = calculateRecMII(NodeSets);
  376. fuseRecs(NodeSets);
  377. // This flag is used for testing and can cause correctness problems.
  378. if (SwpIgnoreRecMII)
  379. RecMII = 0;
  380. setMII(ResMII, RecMII);
  381. setMAX_II();
  382. LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
  383. << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
  384. // Can't schedule a loop without a valid MII.
  385. if (MII == 0) {
  386. LLVM_DEBUG(
  387. dbgs()
  388. << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
  389. NumFailZeroMII++;
  390. return;
  391. }
  392. // Don't pipeline large loops.
  393. if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
  394. LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
  395. << ", we don't pipleline large loops\n");
  396. NumFailLargeMaxMII++;
  397. return;
  398. }
  399. computeNodeFunctions(NodeSets);
  400. registerPressureFilter(NodeSets);
  401. colocateNodeSets(NodeSets);
  402. checkNodeSets(NodeSets);
  403. LLVM_DEBUG({
  404. for (auto &I : NodeSets) {
  405. dbgs() << " Rec NodeSet ";
  406. I.dump();
  407. }
  408. });
  409. llvm::stable_sort(NodeSets, std::greater<NodeSet>());
  410. groupRemainingNodes(NodeSets);
  411. removeDuplicateNodes(NodeSets);
  412. LLVM_DEBUG({
  413. for (auto &I : NodeSets) {
  414. dbgs() << " NodeSet ";
  415. I.dump();
  416. }
  417. });
  418. computeNodeOrder(NodeSets);
  419. // check for node order issues
  420. checkValidNodeOrder(Circuits);
  421. SMSchedule Schedule(Pass.MF);
  422. Scheduled = schedulePipeline(Schedule);
  423. if (!Scheduled){
  424. LLVM_DEBUG(dbgs() << "No schedule found, return\n");
  425. NumFailNoSchedule++;
  426. return;
  427. }
  428. unsigned numStages = Schedule.getMaxStageCount();
  429. // No need to generate pipeline if there are no overlapped iterations.
  430. if (numStages == 0) {
  431. LLVM_DEBUG(
  432. dbgs() << "No overlapped iterations, no need to generate pipeline\n");
  433. NumFailZeroStage++;
  434. return;
  435. }
  436. // Check that the maximum stage count is less than user-defined limit.
  437. if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
  438. LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
  439. << " : too many stages, abort\n");
  440. NumFailLargeMaxStage++;
  441. return;
  442. }
  443. // Generate the schedule as a ModuloSchedule.
  444. DenseMap<MachineInstr *, int> Cycles, Stages;
  445. std::vector<MachineInstr *> OrderedInsts;
  446. for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
  447. ++Cycle) {
  448. for (SUnit *SU : Schedule.getInstructions(Cycle)) {
  449. OrderedInsts.push_back(SU->getInstr());
  450. Cycles[SU->getInstr()] = Cycle;
  451. Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
  452. }
  453. }
  454. DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges;
  455. for (auto &KV : NewMIs) {
  456. Cycles[KV.first] = Cycles[KV.second];
  457. Stages[KV.first] = Stages[KV.second];
  458. NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
  459. }
  460. ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
  461. std::move(Stages));
  462. if (EmitTestAnnotations) {
  463. assert(NewInstrChanges.empty() &&
  464. "Cannot serialize a schedule with InstrChanges!");
  465. ModuloScheduleTestAnnotater MSTI(MF, MS);
  466. MSTI.annotate();
  467. return;
  468. }
  469. // The experimental code generator can't work if there are InstChanges.
  470. if (ExperimentalCodeGen && NewInstrChanges.empty()) {
  471. PeelingModuloScheduleExpander MSE(MF, MS, &LIS);
  472. // Experimental code generation isn't complete yet, but it can partially
  473. // validate the code it generates against the original
  474. // ModuloScheduleExpander.
  475. MSE.validateAgainstModuloScheduleExpander();
  476. } else {
  477. ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
  478. MSE.expand();
  479. MSE.cleanup();
  480. }
  481. ++NumPipelined;
  482. }
  483. /// Clean up after the software pipeliner runs.
  484. void SwingSchedulerDAG::finishBlock() {
  485. for (auto &KV : NewMIs)
  486. MF.DeleteMachineInstr(KV.second);
  487. NewMIs.clear();
  488. // Call the superclass.
  489. ScheduleDAGInstrs::finishBlock();
  490. }
  491. /// Return the register values for the operands of a Phi instruction.
  492. /// This function assume the instruction is a Phi.
  493. static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
  494. unsigned &InitVal, unsigned &LoopVal) {
  495. assert(Phi.isPHI() && "Expecting a Phi.");
  496. InitVal = 0;
  497. LoopVal = 0;
  498. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  499. if (Phi.getOperand(i + 1).getMBB() != Loop)
  500. InitVal = Phi.getOperand(i).getReg();
  501. else
  502. LoopVal = Phi.getOperand(i).getReg();
  503. assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
  504. }
  505. /// Return the Phi register value that comes the loop block.
  506. static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
  507. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  508. if (Phi.getOperand(i + 1).getMBB() == LoopBB)
  509. return Phi.getOperand(i).getReg();
  510. return 0;
  511. }
  512. /// Return true if SUb can be reached from SUa following the chain edges.
  513. static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
  514. SmallPtrSet<SUnit *, 8> Visited;
  515. SmallVector<SUnit *, 8> Worklist;
  516. Worklist.push_back(SUa);
  517. while (!Worklist.empty()) {
  518. const SUnit *SU = Worklist.pop_back_val();
  519. for (auto &SI : SU->Succs) {
  520. SUnit *SuccSU = SI.getSUnit();
  521. if (SI.getKind() == SDep::Order) {
  522. if (Visited.count(SuccSU))
  523. continue;
  524. if (SuccSU == SUb)
  525. return true;
  526. Worklist.push_back(SuccSU);
  527. Visited.insert(SuccSU);
  528. }
  529. }
  530. }
  531. return false;
  532. }
  533. /// Return true if the instruction causes a chain between memory
  534. /// references before and after it.
  535. static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
  536. return MI.isCall() || MI.mayRaiseFPException() ||
  537. MI.hasUnmodeledSideEffects() ||
  538. (MI.hasOrderedMemoryRef() &&
  539. (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
  540. }
  541. /// Return the underlying objects for the memory references of an instruction.
  542. /// This function calls the code in ValueTracking, but first checks that the
  543. /// instruction has a memory operand.
  544. static void getUnderlyingObjects(const MachineInstr *MI,
  545. SmallVectorImpl<const Value *> &Objs,
  546. const DataLayout &DL) {
  547. if (!MI->hasOneMemOperand())
  548. return;
  549. MachineMemOperand *MM = *MI->memoperands_begin();
  550. if (!MM->getValue())
  551. return;
  552. GetUnderlyingObjects(MM->getValue(), Objs, DL);
  553. for (const Value *V : Objs) {
  554. if (!isIdentifiedObject(V)) {
  555. Objs.clear();
  556. return;
  557. }
  558. Objs.push_back(V);
  559. }
  560. }
  561. /// Add a chain edge between a load and store if the store can be an
  562. /// alias of the load on a subsequent iteration, i.e., a loop carried
  563. /// dependence. This code is very similar to the code in ScheduleDAGInstrs
  564. /// but that code doesn't create loop carried dependences.
  565. void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
  566. MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
  567. Value *UnknownValue =
  568. UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
  569. for (auto &SU : SUnits) {
  570. MachineInstr &MI = *SU.getInstr();
  571. if (isDependenceBarrier(MI, AA))
  572. PendingLoads.clear();
  573. else if (MI.mayLoad()) {
  574. SmallVector<const Value *, 4> Objs;
  575. getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
  576. if (Objs.empty())
  577. Objs.push_back(UnknownValue);
  578. for (auto V : Objs) {
  579. SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
  580. SUs.push_back(&SU);
  581. }
  582. } else if (MI.mayStore()) {
  583. SmallVector<const Value *, 4> Objs;
  584. getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
  585. if (Objs.empty())
  586. Objs.push_back(UnknownValue);
  587. for (auto V : Objs) {
  588. MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
  589. PendingLoads.find(V);
  590. if (I == PendingLoads.end())
  591. continue;
  592. for (auto Load : I->second) {
  593. if (isSuccOrder(Load, &SU))
  594. continue;
  595. MachineInstr &LdMI = *Load->getInstr();
  596. // First, perform the cheaper check that compares the base register.
  597. // If they are the same and the load offset is less than the store
  598. // offset, then mark the dependence as loop carried potentially.
  599. const MachineOperand *BaseOp1, *BaseOp2;
  600. int64_t Offset1, Offset2;
  601. if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1, TRI) &&
  602. TII->getMemOperandWithOffset(MI, BaseOp2, Offset2, TRI)) {
  603. if (BaseOp1->isIdenticalTo(*BaseOp2) &&
  604. (int)Offset1 < (int)Offset2) {
  605. assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
  606. "What happened to the chain edge?");
  607. SDep Dep(Load, SDep::Barrier);
  608. Dep.setLatency(1);
  609. SU.addPred(Dep);
  610. continue;
  611. }
  612. }
  613. // Second, the more expensive check that uses alias analysis on the
  614. // base registers. If they alias, and the load offset is less than
  615. // the store offset, the mark the dependence as loop carried.
  616. if (!AA) {
  617. SDep Dep(Load, SDep::Barrier);
  618. Dep.setLatency(1);
  619. SU.addPred(Dep);
  620. continue;
  621. }
  622. MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
  623. MachineMemOperand *MMO2 = *MI.memoperands_begin();
  624. if (!MMO1->getValue() || !MMO2->getValue()) {
  625. SDep Dep(Load, SDep::Barrier);
  626. Dep.setLatency(1);
  627. SU.addPred(Dep);
  628. continue;
  629. }
  630. if (MMO1->getValue() == MMO2->getValue() &&
  631. MMO1->getOffset() <= MMO2->getOffset()) {
  632. SDep Dep(Load, SDep::Barrier);
  633. Dep.setLatency(1);
  634. SU.addPred(Dep);
  635. continue;
  636. }
  637. AliasResult AAResult = AA->alias(
  638. MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
  639. MMO1->getAAInfo()),
  640. MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
  641. MMO2->getAAInfo()));
  642. if (AAResult != NoAlias) {
  643. SDep Dep(Load, SDep::Barrier);
  644. Dep.setLatency(1);
  645. SU.addPred(Dep);
  646. }
  647. }
  648. }
  649. }
  650. }
  651. }
  652. /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
  653. /// processes dependences for PHIs. This function adds true dependences
  654. /// from a PHI to a use, and a loop carried dependence from the use to the
  655. /// PHI. The loop carried dependence is represented as an anti dependence
  656. /// edge. This function also removes chain dependences between unrelated
  657. /// PHIs.
  658. void SwingSchedulerDAG::updatePhiDependences() {
  659. SmallVector<SDep, 4> RemoveDeps;
  660. const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
  661. // Iterate over each DAG node.
  662. for (SUnit &I : SUnits) {
  663. RemoveDeps.clear();
  664. // Set to true if the instruction has an operand defined by a Phi.
  665. unsigned HasPhiUse = 0;
  666. unsigned HasPhiDef = 0;
  667. MachineInstr *MI = I.getInstr();
  668. // Iterate over each operand, and we process the definitions.
  669. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  670. MOE = MI->operands_end();
  671. MOI != MOE; ++MOI) {
  672. if (!MOI->isReg())
  673. continue;
  674. Register Reg = MOI->getReg();
  675. if (MOI->isDef()) {
  676. // If the register is used by a Phi, then create an anti dependence.
  677. for (MachineRegisterInfo::use_instr_iterator
  678. UI = MRI.use_instr_begin(Reg),
  679. UE = MRI.use_instr_end();
  680. UI != UE; ++UI) {
  681. MachineInstr *UseMI = &*UI;
  682. SUnit *SU = getSUnit(UseMI);
  683. if (SU != nullptr && UseMI->isPHI()) {
  684. if (!MI->isPHI()) {
  685. SDep Dep(SU, SDep::Anti, Reg);
  686. Dep.setLatency(1);
  687. I.addPred(Dep);
  688. } else {
  689. HasPhiDef = Reg;
  690. // Add a chain edge to a dependent Phi that isn't an existing
  691. // predecessor.
  692. if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
  693. I.addPred(SDep(SU, SDep::Barrier));
  694. }
  695. }
  696. }
  697. } else if (MOI->isUse()) {
  698. // If the register is defined by a Phi, then create a true dependence.
  699. MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
  700. if (DefMI == nullptr)
  701. continue;
  702. SUnit *SU = getSUnit(DefMI);
  703. if (SU != nullptr && DefMI->isPHI()) {
  704. if (!MI->isPHI()) {
  705. SDep Dep(SU, SDep::Data, Reg);
  706. Dep.setLatency(0);
  707. ST.adjustSchedDependency(SU, &I, Dep);
  708. I.addPred(Dep);
  709. } else {
  710. HasPhiUse = Reg;
  711. // Add a chain edge to a dependent Phi that isn't an existing
  712. // predecessor.
  713. if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
  714. I.addPred(SDep(SU, SDep::Barrier));
  715. }
  716. }
  717. }
  718. }
  719. // Remove order dependences from an unrelated Phi.
  720. if (!SwpPruneDeps)
  721. continue;
  722. for (auto &PI : I.Preds) {
  723. MachineInstr *PMI = PI.getSUnit()->getInstr();
  724. if (PMI->isPHI() && PI.getKind() == SDep::Order) {
  725. if (I.getInstr()->isPHI()) {
  726. if (PMI->getOperand(0).getReg() == HasPhiUse)
  727. continue;
  728. if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
  729. continue;
  730. }
  731. RemoveDeps.push_back(PI);
  732. }
  733. }
  734. for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
  735. I.removePred(RemoveDeps[i]);
  736. }
  737. }
  738. /// Iterate over each DAG node and see if we can change any dependences
  739. /// in order to reduce the recurrence MII.
  740. void SwingSchedulerDAG::changeDependences() {
  741. // See if an instruction can use a value from the previous iteration.
  742. // If so, we update the base and offset of the instruction and change
  743. // the dependences.
  744. for (SUnit &I : SUnits) {
  745. unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
  746. int64_t NewOffset = 0;
  747. if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
  748. NewOffset))
  749. continue;
  750. // Get the MI and SUnit for the instruction that defines the original base.
  751. Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
  752. MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
  753. if (!DefMI)
  754. continue;
  755. SUnit *DefSU = getSUnit(DefMI);
  756. if (!DefSU)
  757. continue;
  758. // Get the MI and SUnit for the instruction that defins the new base.
  759. MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
  760. if (!LastMI)
  761. continue;
  762. SUnit *LastSU = getSUnit(LastMI);
  763. if (!LastSU)
  764. continue;
  765. if (Topo.IsReachable(&I, LastSU))
  766. continue;
  767. // Remove the dependence. The value now depends on a prior iteration.
  768. SmallVector<SDep, 4> Deps;
  769. for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
  770. ++P)
  771. if (P->getSUnit() == DefSU)
  772. Deps.push_back(*P);
  773. for (int i = 0, e = Deps.size(); i != e; i++) {
  774. Topo.RemovePred(&I, Deps[i].getSUnit());
  775. I.removePred(Deps[i]);
  776. }
  777. // Remove the chain dependence between the instructions.
  778. Deps.clear();
  779. for (auto &P : LastSU->Preds)
  780. if (P.getSUnit() == &I && P.getKind() == SDep::Order)
  781. Deps.push_back(P);
  782. for (int i = 0, e = Deps.size(); i != e; i++) {
  783. Topo.RemovePred(LastSU, Deps[i].getSUnit());
  784. LastSU->removePred(Deps[i]);
  785. }
  786. // Add a dependence between the new instruction and the instruction
  787. // that defines the new base.
  788. SDep Dep(&I, SDep::Anti, NewBase);
  789. Topo.AddPred(LastSU, &I);
  790. LastSU->addPred(Dep);
  791. // Remember the base and offset information so that we can update the
  792. // instruction during code generation.
  793. InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
  794. }
  795. }
  796. namespace {
  797. // FuncUnitSorter - Comparison operator used to sort instructions by
  798. // the number of functional unit choices.
  799. struct FuncUnitSorter {
  800. const InstrItineraryData *InstrItins;
  801. const MCSubtargetInfo *STI;
  802. DenseMap<unsigned, unsigned> Resources;
  803. FuncUnitSorter(const TargetSubtargetInfo &TSI)
  804. : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
  805. // Compute the number of functional unit alternatives needed
  806. // at each stage, and take the minimum value. We prioritize the
  807. // instructions by the least number of choices first.
  808. unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
  809. unsigned SchedClass = Inst->getDesc().getSchedClass();
  810. unsigned min = UINT_MAX;
  811. if (InstrItins && !InstrItins->isEmpty()) {
  812. for (const InstrStage &IS :
  813. make_range(InstrItins->beginStage(SchedClass),
  814. InstrItins->endStage(SchedClass))) {
  815. unsigned funcUnits = IS.getUnits();
  816. unsigned numAlternatives = countPopulation(funcUnits);
  817. if (numAlternatives < min) {
  818. min = numAlternatives;
  819. F = funcUnits;
  820. }
  821. }
  822. return min;
  823. }
  824. if (STI && STI->getSchedModel().hasInstrSchedModel()) {
  825. const MCSchedClassDesc *SCDesc =
  826. STI->getSchedModel().getSchedClassDesc(SchedClass);
  827. if (!SCDesc->isValid())
  828. // No valid Schedule Class Desc for schedClass, should be
  829. // Pseudo/PostRAPseudo
  830. return min;
  831. for (const MCWriteProcResEntry &PRE :
  832. make_range(STI->getWriteProcResBegin(SCDesc),
  833. STI->getWriteProcResEnd(SCDesc))) {
  834. if (!PRE.Cycles)
  835. continue;
  836. const MCProcResourceDesc *ProcResource =
  837. STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
  838. unsigned NumUnits = ProcResource->NumUnits;
  839. if (NumUnits < min) {
  840. min = NumUnits;
  841. F = PRE.ProcResourceIdx;
  842. }
  843. }
  844. return min;
  845. }
  846. llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
  847. }
  848. // Compute the critical resources needed by the instruction. This
  849. // function records the functional units needed by instructions that
  850. // must use only one functional unit. We use this as a tie breaker
  851. // for computing the resource MII. The instrutions that require
  852. // the same, highly used, functional unit have high priority.
  853. void calcCriticalResources(MachineInstr &MI) {
  854. unsigned SchedClass = MI.getDesc().getSchedClass();
  855. if (InstrItins && !InstrItins->isEmpty()) {
  856. for (const InstrStage &IS :
  857. make_range(InstrItins->beginStage(SchedClass),
  858. InstrItins->endStage(SchedClass))) {
  859. unsigned FuncUnits = IS.getUnits();
  860. if (countPopulation(FuncUnits) == 1)
  861. Resources[FuncUnits]++;
  862. }
  863. return;
  864. }
  865. if (STI && STI->getSchedModel().hasInstrSchedModel()) {
  866. const MCSchedClassDesc *SCDesc =
  867. STI->getSchedModel().getSchedClassDesc(SchedClass);
  868. if (!SCDesc->isValid())
  869. // No valid Schedule Class Desc for schedClass, should be
  870. // Pseudo/PostRAPseudo
  871. return;
  872. for (const MCWriteProcResEntry &PRE :
  873. make_range(STI->getWriteProcResBegin(SCDesc),
  874. STI->getWriteProcResEnd(SCDesc))) {
  875. if (!PRE.Cycles)
  876. continue;
  877. Resources[PRE.ProcResourceIdx]++;
  878. }
  879. return;
  880. }
  881. llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
  882. }
  883. /// Return true if IS1 has less priority than IS2.
  884. bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
  885. unsigned F1 = 0, F2 = 0;
  886. unsigned MFUs1 = minFuncUnits(IS1, F1);
  887. unsigned MFUs2 = minFuncUnits(IS2, F2);
  888. if (MFUs1 == MFUs2)
  889. return Resources.lookup(F1) < Resources.lookup(F2);
  890. return MFUs1 > MFUs2;
  891. }
  892. };
  893. } // end anonymous namespace
  894. /// Calculate the resource constrained minimum initiation interval for the
  895. /// specified loop. We use the DFA to model the resources needed for
  896. /// each instruction, and we ignore dependences. A different DFA is created
  897. /// for each cycle that is required. When adding a new instruction, we attempt
  898. /// to add it to each existing DFA, until a legal space is found. If the
  899. /// instruction cannot be reserved in an existing DFA, we create a new one.
  900. unsigned SwingSchedulerDAG::calculateResMII() {
  901. LLVM_DEBUG(dbgs() << "calculateResMII:\n");
  902. SmallVector<ResourceManager*, 8> Resources;
  903. MachineBasicBlock *MBB = Loop.getHeader();
  904. Resources.push_back(new ResourceManager(&MF.getSubtarget()));
  905. // Sort the instructions by the number of available choices for scheduling,
  906. // least to most. Use the number of critical resources as the tie breaker.
  907. FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
  908. for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
  909. E = MBB->getFirstTerminator();
  910. I != E; ++I)
  911. FUS.calcCriticalResources(*I);
  912. PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
  913. FuncUnitOrder(FUS);
  914. for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
  915. E = MBB->getFirstTerminator();
  916. I != E; ++I)
  917. FuncUnitOrder.push(&*I);
  918. while (!FuncUnitOrder.empty()) {
  919. MachineInstr *MI = FuncUnitOrder.top();
  920. FuncUnitOrder.pop();
  921. if (TII->isZeroCost(MI->getOpcode()))
  922. continue;
  923. // Attempt to reserve the instruction in an existing DFA. At least one
  924. // DFA is needed for each cycle.
  925. unsigned NumCycles = getSUnit(MI)->Latency;
  926. unsigned ReservedCycles = 0;
  927. SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
  928. SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
  929. LLVM_DEBUG({
  930. dbgs() << "Trying to reserve resource for " << NumCycles
  931. << " cycles for \n";
  932. MI->dump();
  933. });
  934. for (unsigned C = 0; C < NumCycles; ++C)
  935. while (RI != RE) {
  936. if ((*RI)->canReserveResources(*MI)) {
  937. (*RI)->reserveResources(*MI);
  938. ++ReservedCycles;
  939. break;
  940. }
  941. RI++;
  942. }
  943. LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
  944. << ", NumCycles:" << NumCycles << "\n");
  945. // Add new DFAs, if needed, to reserve resources.
  946. for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
  947. LLVM_DEBUG(if (SwpDebugResource) dbgs()
  948. << "NewResource created to reserve resources"
  949. << "\n");
  950. ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
  951. assert(NewResource->canReserveResources(*MI) && "Reserve error.");
  952. NewResource->reserveResources(*MI);
  953. Resources.push_back(NewResource);
  954. }
  955. }
  956. int Resmii = Resources.size();
  957. LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii << "\n");
  958. // Delete the memory for each of the DFAs that were created earlier.
  959. for (ResourceManager *RI : Resources) {
  960. ResourceManager *D = RI;
  961. delete D;
  962. }
  963. Resources.clear();
  964. return Resmii;
  965. }
  966. /// Calculate the recurrence-constrainted minimum initiation interval.
  967. /// Iterate over each circuit. Compute the delay(c) and distance(c)
  968. /// for each circuit. The II needs to satisfy the inequality
  969. /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
  970. /// II that satisfies the inequality, and the RecMII is the maximum
  971. /// of those values.
  972. unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
  973. unsigned RecMII = 0;
  974. for (NodeSet &Nodes : NodeSets) {
  975. if (Nodes.empty())
  976. continue;
  977. unsigned Delay = Nodes.getLatency();
  978. unsigned Distance = 1;
  979. // ii = ceil(delay / distance)
  980. unsigned CurMII = (Delay + Distance - 1) / Distance;
  981. Nodes.setRecMII(CurMII);
  982. if (CurMII > RecMII)
  983. RecMII = CurMII;
  984. }
  985. return RecMII;
  986. }
  987. /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
  988. /// but we do this to find the circuits, and then change them back.
  989. static void swapAntiDependences(std::vector<SUnit> &SUnits) {
  990. SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
  991. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  992. SUnit *SU = &SUnits[i];
  993. for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
  994. IP != EP; ++IP) {
  995. if (IP->getKind() != SDep::Anti)
  996. continue;
  997. DepsAdded.push_back(std::make_pair(SU, *IP));
  998. }
  999. }
  1000. for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
  1001. E = DepsAdded.end();
  1002. I != E; ++I) {
  1003. // Remove this anti dependency and add one in the reverse direction.
  1004. SUnit *SU = I->first;
  1005. SDep &D = I->second;
  1006. SUnit *TargetSU = D.getSUnit();
  1007. unsigned Reg = D.getReg();
  1008. unsigned Lat = D.getLatency();
  1009. SU->removePred(D);
  1010. SDep Dep(SU, SDep::Anti, Reg);
  1011. Dep.setLatency(Lat);
  1012. TargetSU->addPred(Dep);
  1013. }
  1014. }
  1015. /// Create the adjacency structure of the nodes in the graph.
  1016. void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
  1017. SwingSchedulerDAG *DAG) {
  1018. BitVector Added(SUnits.size());
  1019. DenseMap<int, int> OutputDeps;
  1020. for (int i = 0, e = SUnits.size(); i != e; ++i) {
  1021. Added.reset();
  1022. // Add any successor to the adjacency matrix and exclude duplicates.
  1023. for (auto &SI : SUnits[i].Succs) {
  1024. // Only create a back-edge on the first and last nodes of a dependence
  1025. // chain. This records any chains and adds them later.
  1026. if (SI.getKind() == SDep::Output) {
  1027. int N = SI.getSUnit()->NodeNum;
  1028. int BackEdge = i;
  1029. auto Dep = OutputDeps.find(BackEdge);
  1030. if (Dep != OutputDeps.end()) {
  1031. BackEdge = Dep->second;
  1032. OutputDeps.erase(Dep);
  1033. }
  1034. OutputDeps[N] = BackEdge;
  1035. }
  1036. // Do not process a boundary node, an artificial node.
  1037. // A back-edge is processed only if it goes to a Phi.
  1038. if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
  1039. (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
  1040. continue;
  1041. int N = SI.getSUnit()->NodeNum;
  1042. if (!Added.test(N)) {
  1043. AdjK[i].push_back(N);
  1044. Added.set(N);
  1045. }
  1046. }
  1047. // A chain edge between a store and a load is treated as a back-edge in the
  1048. // adjacency matrix.
  1049. for (auto &PI : SUnits[i].Preds) {
  1050. if (!SUnits[i].getInstr()->mayStore() ||
  1051. !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
  1052. continue;
  1053. if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
  1054. int N = PI.getSUnit()->NodeNum;
  1055. if (!Added.test(N)) {
  1056. AdjK[i].push_back(N);
  1057. Added.set(N);
  1058. }
  1059. }
  1060. }
  1061. }
  1062. // Add back-edges in the adjacency matrix for the output dependences.
  1063. for (auto &OD : OutputDeps)
  1064. if (!Added.test(OD.second)) {
  1065. AdjK[OD.first].push_back(OD.second);
  1066. Added.set(OD.second);
  1067. }
  1068. }
  1069. /// Identify an elementary circuit in the dependence graph starting at the
  1070. /// specified node.
  1071. bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
  1072. bool HasBackedge) {
  1073. SUnit *SV = &SUnits[V];
  1074. bool F = false;
  1075. Stack.insert(SV);
  1076. Blocked.set(V);
  1077. for (auto W : AdjK[V]) {
  1078. if (NumPaths > MaxPaths)
  1079. break;
  1080. if (W < S)
  1081. continue;
  1082. if (W == S) {
  1083. if (!HasBackedge)
  1084. NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
  1085. F = true;
  1086. ++NumPaths;
  1087. break;
  1088. } else if (!Blocked.test(W)) {
  1089. if (circuit(W, S, NodeSets,
  1090. Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
  1091. F = true;
  1092. }
  1093. }
  1094. if (F)
  1095. unblock(V);
  1096. else {
  1097. for (auto W : AdjK[V]) {
  1098. if (W < S)
  1099. continue;
  1100. if (B[W].count(SV) == 0)
  1101. B[W].insert(SV);
  1102. }
  1103. }
  1104. Stack.pop_back();
  1105. return F;
  1106. }
  1107. /// Unblock a node in the circuit finding algorithm.
  1108. void SwingSchedulerDAG::Circuits::unblock(int U) {
  1109. Blocked.reset(U);
  1110. SmallPtrSet<SUnit *, 4> &BU = B[U];
  1111. while (!BU.empty()) {
  1112. SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
  1113. assert(SI != BU.end() && "Invalid B set.");
  1114. SUnit *W = *SI;
  1115. BU.erase(W);
  1116. if (Blocked.test(W->NodeNum))
  1117. unblock(W->NodeNum);
  1118. }
  1119. }
  1120. /// Identify all the elementary circuits in the dependence graph using
  1121. /// Johnson's circuit algorithm.
  1122. void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
  1123. // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
  1124. // but we do this to find the circuits, and then change them back.
  1125. swapAntiDependences(SUnits);
  1126. Circuits Cir(SUnits, Topo);
  1127. // Create the adjacency structure.
  1128. Cir.createAdjacencyStructure(this);
  1129. for (int i = 0, e = SUnits.size(); i != e; ++i) {
  1130. Cir.reset();
  1131. Cir.circuit(i, i, NodeSets);
  1132. }
  1133. // Change the dependences back so that we've created a DAG again.
  1134. swapAntiDependences(SUnits);
  1135. }
  1136. // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
  1137. // is loop-carried to the USE in next iteration. This will help pipeliner avoid
  1138. // additional copies that are needed across iterations. An artificial dependence
  1139. // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
  1140. // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
  1141. // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
  1142. // PHI-------True-Dep------> USEOfPhi
  1143. // The mutation creates
  1144. // USEOfPHI -------Artificial-Dep---> SRCOfCopy
  1145. // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
  1146. // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
  1147. // late to avoid additional copies across iterations. The possible scheduling
  1148. // order would be
  1149. // USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
  1150. void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
  1151. for (SUnit &SU : DAG->SUnits) {
  1152. // Find the COPY/REG_SEQUENCE instruction.
  1153. if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
  1154. continue;
  1155. // Record the loop carried PHIs.
  1156. SmallVector<SUnit *, 4> PHISUs;
  1157. // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
  1158. SmallVector<SUnit *, 4> SrcSUs;
  1159. for (auto &Dep : SU.Preds) {
  1160. SUnit *TmpSU = Dep.getSUnit();
  1161. MachineInstr *TmpMI = TmpSU->getInstr();
  1162. SDep::Kind DepKind = Dep.getKind();
  1163. // Save the loop carried PHI.
  1164. if (DepKind == SDep::Anti && TmpMI->isPHI())
  1165. PHISUs.push_back(TmpSU);
  1166. // Save the source of COPY/REG_SEQUENCE.
  1167. // If the source has no pre-decessors, we will end up creating cycles.
  1168. else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
  1169. SrcSUs.push_back(TmpSU);
  1170. }
  1171. if (PHISUs.size() == 0 || SrcSUs.size() == 0)
  1172. continue;
  1173. // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
  1174. // SUnit to the container.
  1175. SmallVector<SUnit *, 8> UseSUs;
  1176. for (auto I = PHISUs.begin(); I != PHISUs.end(); ++I) {
  1177. for (auto &Dep : (*I)->Succs) {
  1178. if (Dep.getKind() != SDep::Data)
  1179. continue;
  1180. SUnit *TmpSU = Dep.getSUnit();
  1181. MachineInstr *TmpMI = TmpSU->getInstr();
  1182. if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
  1183. PHISUs.push_back(TmpSU);
  1184. continue;
  1185. }
  1186. UseSUs.push_back(TmpSU);
  1187. }
  1188. }
  1189. if (UseSUs.size() == 0)
  1190. continue;
  1191. SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
  1192. // Add the artificial dependencies if it does not form a cycle.
  1193. for (auto I : UseSUs) {
  1194. for (auto Src : SrcSUs) {
  1195. if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
  1196. Src->addPred(SDep(I, SDep::Artificial));
  1197. SDAG->Topo.AddPred(Src, I);
  1198. }
  1199. }
  1200. }
  1201. }
  1202. }
  1203. /// Return true for DAG nodes that we ignore when computing the cost functions.
  1204. /// We ignore the back-edge recurrence in order to avoid unbounded recursion
  1205. /// in the calculation of the ASAP, ALAP, etc functions.
  1206. static bool ignoreDependence(const SDep &D, bool isPred) {
  1207. if (D.isArtificial())
  1208. return true;
  1209. return D.getKind() == SDep::Anti && isPred;
  1210. }
  1211. /// Compute several functions need to order the nodes for scheduling.
  1212. /// ASAP - Earliest time to schedule a node.
  1213. /// ALAP - Latest time to schedule a node.
  1214. /// MOV - Mobility function, difference between ALAP and ASAP.
  1215. /// D - Depth of each node.
  1216. /// H - Height of each node.
  1217. void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
  1218. ScheduleInfo.resize(SUnits.size());
  1219. LLVM_DEBUG({
  1220. for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
  1221. E = Topo.end();
  1222. I != E; ++I) {
  1223. const SUnit &SU = SUnits[*I];
  1224. dumpNode(SU);
  1225. }
  1226. });
  1227. int maxASAP = 0;
  1228. // Compute ASAP and ZeroLatencyDepth.
  1229. for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
  1230. E = Topo.end();
  1231. I != E; ++I) {
  1232. int asap = 0;
  1233. int zeroLatencyDepth = 0;
  1234. SUnit *SU = &SUnits[*I];
  1235. for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
  1236. EP = SU->Preds.end();
  1237. IP != EP; ++IP) {
  1238. SUnit *pred = IP->getSUnit();
  1239. if (IP->getLatency() == 0)
  1240. zeroLatencyDepth =
  1241. std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
  1242. if (ignoreDependence(*IP, true))
  1243. continue;
  1244. asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
  1245. getDistance(pred, SU, *IP) * MII));
  1246. }
  1247. maxASAP = std::max(maxASAP, asap);
  1248. ScheduleInfo[*I].ASAP = asap;
  1249. ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
  1250. }
  1251. // Compute ALAP, ZeroLatencyHeight, and MOV.
  1252. for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
  1253. E = Topo.rend();
  1254. I != E; ++I) {
  1255. int alap = maxASAP;
  1256. int zeroLatencyHeight = 0;
  1257. SUnit *SU = &SUnits[*I];
  1258. for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
  1259. ES = SU->Succs.end();
  1260. IS != ES; ++IS) {
  1261. SUnit *succ = IS->getSUnit();
  1262. if (IS->getLatency() == 0)
  1263. zeroLatencyHeight =
  1264. std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
  1265. if (ignoreDependence(*IS, true))
  1266. continue;
  1267. alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
  1268. getDistance(SU, succ, *IS) * MII));
  1269. }
  1270. ScheduleInfo[*I].ALAP = alap;
  1271. ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
  1272. }
  1273. // After computing the node functions, compute the summary for each node set.
  1274. for (NodeSet &I : NodeSets)
  1275. I.computeNodeSetInfo(this);
  1276. LLVM_DEBUG({
  1277. for (unsigned i = 0; i < SUnits.size(); i++) {
  1278. dbgs() << "\tNode " << i << ":\n";
  1279. dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
  1280. dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
  1281. dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
  1282. dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
  1283. dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
  1284. dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
  1285. dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
  1286. }
  1287. });
  1288. }
  1289. /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
  1290. /// as the predecessors of the elements of NodeOrder that are not also in
  1291. /// NodeOrder.
  1292. static bool pred_L(SetVector<SUnit *> &NodeOrder,
  1293. SmallSetVector<SUnit *, 8> &Preds,
  1294. const NodeSet *S = nullptr) {
  1295. Preds.clear();
  1296. for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
  1297. I != E; ++I) {
  1298. for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
  1299. PI != PE; ++PI) {
  1300. if (S && S->count(PI->getSUnit()) == 0)
  1301. continue;
  1302. if (ignoreDependence(*PI, true))
  1303. continue;
  1304. if (NodeOrder.count(PI->getSUnit()) == 0)
  1305. Preds.insert(PI->getSUnit());
  1306. }
  1307. // Back-edges are predecessors with an anti-dependence.
  1308. for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
  1309. ES = (*I)->Succs.end();
  1310. IS != ES; ++IS) {
  1311. if (IS->getKind() != SDep::Anti)
  1312. continue;
  1313. if (S && S->count(IS->getSUnit()) == 0)
  1314. continue;
  1315. if (NodeOrder.count(IS->getSUnit()) == 0)
  1316. Preds.insert(IS->getSUnit());
  1317. }
  1318. }
  1319. return !Preds.empty();
  1320. }
  1321. /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
  1322. /// as the successors of the elements of NodeOrder that are not also in
  1323. /// NodeOrder.
  1324. static bool succ_L(SetVector<SUnit *> &NodeOrder,
  1325. SmallSetVector<SUnit *, 8> &Succs,
  1326. const NodeSet *S = nullptr) {
  1327. Succs.clear();
  1328. for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
  1329. I != E; ++I) {
  1330. for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
  1331. SI != SE; ++SI) {
  1332. if (S && S->count(SI->getSUnit()) == 0)
  1333. continue;
  1334. if (ignoreDependence(*SI, false))
  1335. continue;
  1336. if (NodeOrder.count(SI->getSUnit()) == 0)
  1337. Succs.insert(SI->getSUnit());
  1338. }
  1339. for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
  1340. PE = (*I)->Preds.end();
  1341. PI != PE; ++PI) {
  1342. if (PI->getKind() != SDep::Anti)
  1343. continue;
  1344. if (S && S->count(PI->getSUnit()) == 0)
  1345. continue;
  1346. if (NodeOrder.count(PI->getSUnit()) == 0)
  1347. Succs.insert(PI->getSUnit());
  1348. }
  1349. }
  1350. return !Succs.empty();
  1351. }
  1352. /// Return true if there is a path from the specified node to any of the nodes
  1353. /// in DestNodes. Keep track and return the nodes in any path.
  1354. static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
  1355. SetVector<SUnit *> &DestNodes,
  1356. SetVector<SUnit *> &Exclude,
  1357. SmallPtrSet<SUnit *, 8> &Visited) {
  1358. if (Cur->isBoundaryNode())
  1359. return false;
  1360. if (Exclude.count(Cur) != 0)
  1361. return false;
  1362. if (DestNodes.count(Cur) != 0)
  1363. return true;
  1364. if (!Visited.insert(Cur).second)
  1365. return Path.count(Cur) != 0;
  1366. bool FoundPath = false;
  1367. for (auto &SI : Cur->Succs)
  1368. FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
  1369. for (auto &PI : Cur->Preds)
  1370. if (PI.getKind() == SDep::Anti)
  1371. FoundPath |=
  1372. computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
  1373. if (FoundPath)
  1374. Path.insert(Cur);
  1375. return FoundPath;
  1376. }
  1377. /// Return true if Set1 is a subset of Set2.
  1378. template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
  1379. for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
  1380. if (Set2.count(*I) == 0)
  1381. return false;
  1382. return true;
  1383. }
  1384. /// Compute the live-out registers for the instructions in a node-set.
  1385. /// The live-out registers are those that are defined in the node-set,
  1386. /// but not used. Except for use operands of Phis.
  1387. static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
  1388. NodeSet &NS) {
  1389. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1390. MachineRegisterInfo &MRI = MF.getRegInfo();
  1391. SmallVector<RegisterMaskPair, 8> LiveOutRegs;
  1392. SmallSet<unsigned, 4> Uses;
  1393. for (SUnit *SU : NS) {
  1394. const MachineInstr *MI = SU->getInstr();
  1395. if (MI->isPHI())
  1396. continue;
  1397. for (const MachineOperand &MO : MI->operands())
  1398. if (MO.isReg() && MO.isUse()) {
  1399. Register Reg = MO.getReg();
  1400. if (Register::isVirtualRegister(Reg))
  1401. Uses.insert(Reg);
  1402. else if (MRI.isAllocatable(Reg))
  1403. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  1404. Uses.insert(*Units);
  1405. }
  1406. }
  1407. for (SUnit *SU : NS)
  1408. for (const MachineOperand &MO : SU->getInstr()->operands())
  1409. if (MO.isReg() && MO.isDef() && !MO.isDead()) {
  1410. Register Reg = MO.getReg();
  1411. if (Register::isVirtualRegister(Reg)) {
  1412. if (!Uses.count(Reg))
  1413. LiveOutRegs.push_back(RegisterMaskPair(Reg,
  1414. LaneBitmask::getNone()));
  1415. } else if (MRI.isAllocatable(Reg)) {
  1416. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  1417. if (!Uses.count(*Units))
  1418. LiveOutRegs.push_back(RegisterMaskPair(*Units,
  1419. LaneBitmask::getNone()));
  1420. }
  1421. }
  1422. RPTracker.addLiveRegs(LiveOutRegs);
  1423. }
  1424. /// A heuristic to filter nodes in recurrent node-sets if the register
  1425. /// pressure of a set is too high.
  1426. void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
  1427. for (auto &NS : NodeSets) {
  1428. // Skip small node-sets since they won't cause register pressure problems.
  1429. if (NS.size() <= 2)
  1430. continue;
  1431. IntervalPressure RecRegPressure;
  1432. RegPressureTracker RecRPTracker(RecRegPressure);
  1433. RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
  1434. computeLiveOuts(MF, RecRPTracker, NS);
  1435. RecRPTracker.closeBottom();
  1436. std::vector<SUnit *> SUnits(NS.begin(), NS.end());
  1437. llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
  1438. return A->NodeNum > B->NodeNum;
  1439. });
  1440. for (auto &SU : SUnits) {
  1441. // Since we're computing the register pressure for a subset of the
  1442. // instructions in a block, we need to set the tracker for each
  1443. // instruction in the node-set. The tracker is set to the instruction
  1444. // just after the one we're interested in.
  1445. MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
  1446. RecRPTracker.setPos(std::next(CurInstI));
  1447. RegPressureDelta RPDelta;
  1448. ArrayRef<PressureChange> CriticalPSets;
  1449. RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
  1450. CriticalPSets,
  1451. RecRegPressure.MaxSetPressure);
  1452. if (RPDelta.Excess.isValid()) {
  1453. LLVM_DEBUG(
  1454. dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
  1455. << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
  1456. << ":" << RPDelta.Excess.getUnitInc());
  1457. NS.setExceedPressure(SU);
  1458. break;
  1459. }
  1460. RecRPTracker.recede();
  1461. }
  1462. }
  1463. }
  1464. /// A heuristic to colocate node sets that have the same set of
  1465. /// successors.
  1466. void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
  1467. unsigned Colocate = 0;
  1468. for (int i = 0, e = NodeSets.size(); i < e; ++i) {
  1469. NodeSet &N1 = NodeSets[i];
  1470. SmallSetVector<SUnit *, 8> S1;
  1471. if (N1.empty() || !succ_L(N1, S1))
  1472. continue;
  1473. for (int j = i + 1; j < e; ++j) {
  1474. NodeSet &N2 = NodeSets[j];
  1475. if (N1.compareRecMII(N2) != 0)
  1476. continue;
  1477. SmallSetVector<SUnit *, 8> S2;
  1478. if (N2.empty() || !succ_L(N2, S2))
  1479. continue;
  1480. if (isSubset(S1, S2) && S1.size() == S2.size()) {
  1481. N1.setColocate(++Colocate);
  1482. N2.setColocate(Colocate);
  1483. break;
  1484. }
  1485. }
  1486. }
  1487. }
  1488. /// Check if the existing node-sets are profitable. If not, then ignore the
  1489. /// recurrent node-sets, and attempt to schedule all nodes together. This is
  1490. /// a heuristic. If the MII is large and all the recurrent node-sets are small,
  1491. /// then it's best to try to schedule all instructions together instead of
  1492. /// starting with the recurrent node-sets.
  1493. void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
  1494. // Look for loops with a large MII.
  1495. if (MII < 17)
  1496. return;
  1497. // Check if the node-set contains only a simple add recurrence.
  1498. for (auto &NS : NodeSets) {
  1499. if (NS.getRecMII() > 2)
  1500. return;
  1501. if (NS.getMaxDepth() > MII)
  1502. return;
  1503. }
  1504. NodeSets.clear();
  1505. LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
  1506. return;
  1507. }
  1508. /// Add the nodes that do not belong to a recurrence set into groups
  1509. /// based upon connected componenets.
  1510. void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
  1511. SetVector<SUnit *> NodesAdded;
  1512. SmallPtrSet<SUnit *, 8> Visited;
  1513. // Add the nodes that are on a path between the previous node sets and
  1514. // the current node set.
  1515. for (NodeSet &I : NodeSets) {
  1516. SmallSetVector<SUnit *, 8> N;
  1517. // Add the nodes from the current node set to the previous node set.
  1518. if (succ_L(I, N)) {
  1519. SetVector<SUnit *> Path;
  1520. for (SUnit *NI : N) {
  1521. Visited.clear();
  1522. computePath(NI, Path, NodesAdded, I, Visited);
  1523. }
  1524. if (!Path.empty())
  1525. I.insert(Path.begin(), Path.end());
  1526. }
  1527. // Add the nodes from the previous node set to the current node set.
  1528. N.clear();
  1529. if (succ_L(NodesAdded, N)) {
  1530. SetVector<SUnit *> Path;
  1531. for (SUnit *NI : N) {
  1532. Visited.clear();
  1533. computePath(NI, Path, I, NodesAdded, Visited);
  1534. }
  1535. if (!Path.empty())
  1536. I.insert(Path.begin(), Path.end());
  1537. }
  1538. NodesAdded.insert(I.begin(), I.end());
  1539. }
  1540. // Create a new node set with the connected nodes of any successor of a node
  1541. // in a recurrent set.
  1542. NodeSet NewSet;
  1543. SmallSetVector<SUnit *, 8> N;
  1544. if (succ_L(NodesAdded, N))
  1545. for (SUnit *I : N)
  1546. addConnectedNodes(I, NewSet, NodesAdded);
  1547. if (!NewSet.empty())
  1548. NodeSets.push_back(NewSet);
  1549. // Create a new node set with the connected nodes of any predecessor of a node
  1550. // in a recurrent set.
  1551. NewSet.clear();
  1552. if (pred_L(NodesAdded, N))
  1553. for (SUnit *I : N)
  1554. addConnectedNodes(I, NewSet, NodesAdded);
  1555. if (!NewSet.empty())
  1556. NodeSets.push_back(NewSet);
  1557. // Create new nodes sets with the connected nodes any remaining node that
  1558. // has no predecessor.
  1559. for (unsigned i = 0; i < SUnits.size(); ++i) {
  1560. SUnit *SU = &SUnits[i];
  1561. if (NodesAdded.count(SU) == 0) {
  1562. NewSet.clear();
  1563. addConnectedNodes(SU, NewSet, NodesAdded);
  1564. if (!NewSet.empty())
  1565. NodeSets.push_back(NewSet);
  1566. }
  1567. }
  1568. }
  1569. /// Add the node to the set, and add all of its connected nodes to the set.
  1570. void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
  1571. SetVector<SUnit *> &NodesAdded) {
  1572. NewSet.insert(SU);
  1573. NodesAdded.insert(SU);
  1574. for (auto &SI : SU->Succs) {
  1575. SUnit *Successor = SI.getSUnit();
  1576. if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
  1577. addConnectedNodes(Successor, NewSet, NodesAdded);
  1578. }
  1579. for (auto &PI : SU->Preds) {
  1580. SUnit *Predecessor = PI.getSUnit();
  1581. if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
  1582. addConnectedNodes(Predecessor, NewSet, NodesAdded);
  1583. }
  1584. }
  1585. /// Return true if Set1 contains elements in Set2. The elements in common
  1586. /// are returned in a different container.
  1587. static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
  1588. SmallSetVector<SUnit *, 8> &Result) {
  1589. Result.clear();
  1590. for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
  1591. SUnit *SU = Set1[i];
  1592. if (Set2.count(SU) != 0)
  1593. Result.insert(SU);
  1594. }
  1595. return !Result.empty();
  1596. }
  1597. /// Merge the recurrence node sets that have the same initial node.
  1598. void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
  1599. for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
  1600. ++I) {
  1601. NodeSet &NI = *I;
  1602. for (NodeSetType::iterator J = I + 1; J != E;) {
  1603. NodeSet &NJ = *J;
  1604. if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
  1605. if (NJ.compareRecMII(NI) > 0)
  1606. NI.setRecMII(NJ.getRecMII());
  1607. for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
  1608. ++NII)
  1609. I->insert(*NII);
  1610. NodeSets.erase(J);
  1611. E = NodeSets.end();
  1612. } else {
  1613. ++J;
  1614. }
  1615. }
  1616. }
  1617. }
  1618. /// Remove nodes that have been scheduled in previous NodeSets.
  1619. void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
  1620. for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
  1621. ++I)
  1622. for (NodeSetType::iterator J = I + 1; J != E;) {
  1623. J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
  1624. if (J->empty()) {
  1625. NodeSets.erase(J);
  1626. E = NodeSets.end();
  1627. } else {
  1628. ++J;
  1629. }
  1630. }
  1631. }
  1632. /// Compute an ordered list of the dependence graph nodes, which
  1633. /// indicates the order that the nodes will be scheduled. This is a
  1634. /// two-level algorithm. First, a partial order is created, which
  1635. /// consists of a list of sets ordered from highest to lowest priority.
  1636. void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
  1637. SmallSetVector<SUnit *, 8> R;
  1638. NodeOrder.clear();
  1639. for (auto &Nodes : NodeSets) {
  1640. LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
  1641. OrderKind Order;
  1642. SmallSetVector<SUnit *, 8> N;
  1643. if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
  1644. R.insert(N.begin(), N.end());
  1645. Order = BottomUp;
  1646. LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
  1647. } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
  1648. R.insert(N.begin(), N.end());
  1649. Order = TopDown;
  1650. LLVM_DEBUG(dbgs() << " Top down (succs) ");
  1651. } else if (isIntersect(N, Nodes, R)) {
  1652. // If some of the successors are in the existing node-set, then use the
  1653. // top-down ordering.
  1654. Order = TopDown;
  1655. LLVM_DEBUG(dbgs() << " Top down (intersect) ");
  1656. } else if (NodeSets.size() == 1) {
  1657. for (auto &N : Nodes)
  1658. if (N->Succs.size() == 0)
  1659. R.insert(N);
  1660. Order = BottomUp;
  1661. LLVM_DEBUG(dbgs() << " Bottom up (all) ");
  1662. } else {
  1663. // Find the node with the highest ASAP.
  1664. SUnit *maxASAP = nullptr;
  1665. for (SUnit *SU : Nodes) {
  1666. if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
  1667. (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
  1668. maxASAP = SU;
  1669. }
  1670. R.insert(maxASAP);
  1671. Order = BottomUp;
  1672. LLVM_DEBUG(dbgs() << " Bottom up (default) ");
  1673. }
  1674. while (!R.empty()) {
  1675. if (Order == TopDown) {
  1676. // Choose the node with the maximum height. If more than one, choose
  1677. // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
  1678. // choose the node with the lowest MOV.
  1679. while (!R.empty()) {
  1680. SUnit *maxHeight = nullptr;
  1681. for (SUnit *I : R) {
  1682. if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
  1683. maxHeight = I;
  1684. else if (getHeight(I) == getHeight(maxHeight) &&
  1685. getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
  1686. maxHeight = I;
  1687. else if (getHeight(I) == getHeight(maxHeight) &&
  1688. getZeroLatencyHeight(I) ==
  1689. getZeroLatencyHeight(maxHeight) &&
  1690. getMOV(I) < getMOV(maxHeight))
  1691. maxHeight = I;
  1692. }
  1693. NodeOrder.insert(maxHeight);
  1694. LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
  1695. R.remove(maxHeight);
  1696. for (const auto &I : maxHeight->Succs) {
  1697. if (Nodes.count(I.getSUnit()) == 0)
  1698. continue;
  1699. if (NodeOrder.count(I.getSUnit()) != 0)
  1700. continue;
  1701. if (ignoreDependence(I, false))
  1702. continue;
  1703. R.insert(I.getSUnit());
  1704. }
  1705. // Back-edges are predecessors with an anti-dependence.
  1706. for (const auto &I : maxHeight->Preds) {
  1707. if (I.getKind() != SDep::Anti)
  1708. continue;
  1709. if (Nodes.count(I.getSUnit()) == 0)
  1710. continue;
  1711. if (NodeOrder.count(I.getSUnit()) != 0)
  1712. continue;
  1713. R.insert(I.getSUnit());
  1714. }
  1715. }
  1716. Order = BottomUp;
  1717. LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
  1718. SmallSetVector<SUnit *, 8> N;
  1719. if (pred_L(NodeOrder, N, &Nodes))
  1720. R.insert(N.begin(), N.end());
  1721. } else {
  1722. // Choose the node with the maximum depth. If more than one, choose
  1723. // the node with the maximum ZeroLatencyDepth. If still more than one,
  1724. // choose the node with the lowest MOV.
  1725. while (!R.empty()) {
  1726. SUnit *maxDepth = nullptr;
  1727. for (SUnit *I : R) {
  1728. if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
  1729. maxDepth = I;
  1730. else if (getDepth(I) == getDepth(maxDepth) &&
  1731. getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
  1732. maxDepth = I;
  1733. else if (getDepth(I) == getDepth(maxDepth) &&
  1734. getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
  1735. getMOV(I) < getMOV(maxDepth))
  1736. maxDepth = I;
  1737. }
  1738. NodeOrder.insert(maxDepth);
  1739. LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
  1740. R.remove(maxDepth);
  1741. if (Nodes.isExceedSU(maxDepth)) {
  1742. Order = TopDown;
  1743. R.clear();
  1744. R.insert(Nodes.getNode(0));
  1745. break;
  1746. }
  1747. for (const auto &I : maxDepth->Preds) {
  1748. if (Nodes.count(I.getSUnit()) == 0)
  1749. continue;
  1750. if (NodeOrder.count(I.getSUnit()) != 0)
  1751. continue;
  1752. R.insert(I.getSUnit());
  1753. }
  1754. // Back-edges are predecessors with an anti-dependence.
  1755. for (const auto &I : maxDepth->Succs) {
  1756. if (I.getKind() != SDep::Anti)
  1757. continue;
  1758. if (Nodes.count(I.getSUnit()) == 0)
  1759. continue;
  1760. if (NodeOrder.count(I.getSUnit()) != 0)
  1761. continue;
  1762. R.insert(I.getSUnit());
  1763. }
  1764. }
  1765. Order = TopDown;
  1766. LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
  1767. SmallSetVector<SUnit *, 8> N;
  1768. if (succ_L(NodeOrder, N, &Nodes))
  1769. R.insert(N.begin(), N.end());
  1770. }
  1771. }
  1772. LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
  1773. }
  1774. LLVM_DEBUG({
  1775. dbgs() << "Node order: ";
  1776. for (SUnit *I : NodeOrder)
  1777. dbgs() << " " << I->NodeNum << " ";
  1778. dbgs() << "\n";
  1779. });
  1780. }
  1781. /// Process the nodes in the computed order and create the pipelined schedule
  1782. /// of the instructions, if possible. Return true if a schedule is found.
  1783. bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
  1784. if (NodeOrder.empty()){
  1785. LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
  1786. return false;
  1787. }
  1788. bool scheduleFound = false;
  1789. unsigned II = 0;
  1790. // Keep increasing II until a valid schedule is found.
  1791. for (II = MII; II <= MAX_II && !scheduleFound; ++II) {
  1792. Schedule.reset();
  1793. Schedule.setInitiationInterval(II);
  1794. LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
  1795. SetVector<SUnit *>::iterator NI = NodeOrder.begin();
  1796. SetVector<SUnit *>::iterator NE = NodeOrder.end();
  1797. do {
  1798. SUnit *SU = *NI;
  1799. // Compute the schedule time for the instruction, which is based
  1800. // upon the scheduled time for any predecessors/successors.
  1801. int EarlyStart = INT_MIN;
  1802. int LateStart = INT_MAX;
  1803. // These values are set when the size of the schedule window is limited
  1804. // due to chain dependences.
  1805. int SchedEnd = INT_MAX;
  1806. int SchedStart = INT_MIN;
  1807. Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
  1808. II, this);
  1809. LLVM_DEBUG({
  1810. dbgs() << "\n";
  1811. dbgs() << "Inst (" << SU->NodeNum << ") ";
  1812. SU->getInstr()->dump();
  1813. dbgs() << "\n";
  1814. });
  1815. LLVM_DEBUG({
  1816. dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
  1817. LateStart, SchedEnd, SchedStart);
  1818. });
  1819. if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
  1820. SchedStart > LateStart)
  1821. scheduleFound = false;
  1822. else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
  1823. SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
  1824. scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
  1825. } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
  1826. SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
  1827. scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
  1828. } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
  1829. SchedEnd =
  1830. std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
  1831. // When scheduling a Phi it is better to start at the late cycle and go
  1832. // backwards. The default order may insert the Phi too far away from
  1833. // its first dependence.
  1834. if (SU->getInstr()->isPHI())
  1835. scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
  1836. else
  1837. scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
  1838. } else {
  1839. int FirstCycle = Schedule.getFirstCycle();
  1840. scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
  1841. FirstCycle + getASAP(SU) + II - 1, II);
  1842. }
  1843. // Even if we find a schedule, make sure the schedule doesn't exceed the
  1844. // allowable number of stages. We keep trying if this happens.
  1845. if (scheduleFound)
  1846. if (SwpMaxStages > -1 &&
  1847. Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
  1848. scheduleFound = false;
  1849. LLVM_DEBUG({
  1850. if (!scheduleFound)
  1851. dbgs() << "\tCan't schedule\n";
  1852. });
  1853. } while (++NI != NE && scheduleFound);
  1854. // If a schedule is found, check if it is a valid schedule too.
  1855. if (scheduleFound)
  1856. scheduleFound = Schedule.isValidSchedule(this);
  1857. }
  1858. LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << " (II=" << II
  1859. << ")\n");
  1860. if (scheduleFound)
  1861. Schedule.finalizeSchedule(this);
  1862. else
  1863. Schedule.reset();
  1864. return scheduleFound && Schedule.getMaxStageCount() > 0;
  1865. }
  1866. /// Return true if we can compute the amount the instruction changes
  1867. /// during each iteration. Set Delta to the amount of the change.
  1868. bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
  1869. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1870. const MachineOperand *BaseOp;
  1871. int64_t Offset;
  1872. if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
  1873. return false;
  1874. if (!BaseOp->isReg())
  1875. return false;
  1876. Register BaseReg = BaseOp->getReg();
  1877. MachineRegisterInfo &MRI = MF.getRegInfo();
  1878. // Check if there is a Phi. If so, get the definition in the loop.
  1879. MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
  1880. if (BaseDef && BaseDef->isPHI()) {
  1881. BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
  1882. BaseDef = MRI.getVRegDef(BaseReg);
  1883. }
  1884. if (!BaseDef)
  1885. return false;
  1886. int D = 0;
  1887. if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
  1888. return false;
  1889. Delta = D;
  1890. return true;
  1891. }
  1892. /// Check if we can change the instruction to use an offset value from the
  1893. /// previous iteration. If so, return true and set the base and offset values
  1894. /// so that we can rewrite the load, if necessary.
  1895. /// v1 = Phi(v0, v3)
  1896. /// v2 = load v1, 0
  1897. /// v3 = post_store v1, 4, x
  1898. /// This function enables the load to be rewritten as v2 = load v3, 4.
  1899. bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
  1900. unsigned &BasePos,
  1901. unsigned &OffsetPos,
  1902. unsigned &NewBase,
  1903. int64_t &Offset) {
  1904. // Get the load instruction.
  1905. if (TII->isPostIncrement(*MI))
  1906. return false;
  1907. unsigned BasePosLd, OffsetPosLd;
  1908. if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
  1909. return false;
  1910. Register BaseReg = MI->getOperand(BasePosLd).getReg();
  1911. // Look for the Phi instruction.
  1912. MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
  1913. MachineInstr *Phi = MRI.getVRegDef(BaseReg);
  1914. if (!Phi || !Phi->isPHI())
  1915. return false;
  1916. // Get the register defined in the loop block.
  1917. unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
  1918. if (!PrevReg)
  1919. return false;
  1920. // Check for the post-increment load/store instruction.
  1921. MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
  1922. if (!PrevDef || PrevDef == MI)
  1923. return false;
  1924. if (!TII->isPostIncrement(*PrevDef))
  1925. return false;
  1926. unsigned BasePos1 = 0, OffsetPos1 = 0;
  1927. if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
  1928. return false;
  1929. // Make sure that the instructions do not access the same memory location in
  1930. // the next iteration.
  1931. int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
  1932. int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
  1933. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  1934. NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
  1935. bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
  1936. MF.DeleteMachineInstr(NewMI);
  1937. if (!Disjoint)
  1938. return false;
  1939. // Set the return value once we determine that we return true.
  1940. BasePos = BasePosLd;
  1941. OffsetPos = OffsetPosLd;
  1942. NewBase = PrevReg;
  1943. Offset = StoreOffset;
  1944. return true;
  1945. }
  1946. /// Apply changes to the instruction if needed. The changes are need
  1947. /// to improve the scheduling and depend up on the final schedule.
  1948. void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
  1949. SMSchedule &Schedule) {
  1950. SUnit *SU = getSUnit(MI);
  1951. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  1952. InstrChanges.find(SU);
  1953. if (It != InstrChanges.end()) {
  1954. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  1955. unsigned BasePos, OffsetPos;
  1956. if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  1957. return;
  1958. Register BaseReg = MI->getOperand(BasePos).getReg();
  1959. MachineInstr *LoopDef = findDefInLoop(BaseReg);
  1960. int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
  1961. int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
  1962. int BaseStageNum = Schedule.stageScheduled(SU);
  1963. int BaseCycleNum = Schedule.cycleScheduled(SU);
  1964. if (BaseStageNum < DefStageNum) {
  1965. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  1966. int OffsetDiff = DefStageNum - BaseStageNum;
  1967. if (DefCycleNum < BaseCycleNum) {
  1968. NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
  1969. if (OffsetDiff > 0)
  1970. --OffsetDiff;
  1971. }
  1972. int64_t NewOffset =
  1973. MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
  1974. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  1975. SU->setInstr(NewMI);
  1976. MISUnitMap[NewMI] = SU;
  1977. NewMIs[MI] = NewMI;
  1978. }
  1979. }
  1980. }
  1981. /// Return the instruction in the loop that defines the register.
  1982. /// If the definition is a Phi, then follow the Phi operand to
  1983. /// the instruction in the loop.
  1984. MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
  1985. SmallPtrSet<MachineInstr *, 8> Visited;
  1986. MachineInstr *Def = MRI.getVRegDef(Reg);
  1987. while (Def->isPHI()) {
  1988. if (!Visited.insert(Def).second)
  1989. break;
  1990. for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
  1991. if (Def->getOperand(i + 1).getMBB() == BB) {
  1992. Def = MRI.getVRegDef(Def->getOperand(i).getReg());
  1993. break;
  1994. }
  1995. }
  1996. return Def;
  1997. }
  1998. /// Return true for an order or output dependence that is loop carried
  1999. /// potentially. A dependence is loop carried if the destination defines a valu
  2000. /// that may be used or defined by the source in a subsequent iteration.
  2001. bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
  2002. bool isSucc) {
  2003. if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
  2004. Dep.isArtificial())
  2005. return false;
  2006. if (!SwpPruneLoopCarried)
  2007. return true;
  2008. if (Dep.getKind() == SDep::Output)
  2009. return true;
  2010. MachineInstr *SI = Source->getInstr();
  2011. MachineInstr *DI = Dep.getSUnit()->getInstr();
  2012. if (!isSucc)
  2013. std::swap(SI, DI);
  2014. assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
  2015. // Assume ordered loads and stores may have a loop carried dependence.
  2016. if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
  2017. SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
  2018. SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
  2019. return true;
  2020. // Only chain dependences between a load and store can be loop carried.
  2021. if (!DI->mayStore() || !SI->mayLoad())
  2022. return false;
  2023. unsigned DeltaS, DeltaD;
  2024. if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
  2025. return true;
  2026. const MachineOperand *BaseOpS, *BaseOpD;
  2027. int64_t OffsetS, OffsetD;
  2028. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2029. if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, TRI) ||
  2030. !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, TRI))
  2031. return true;
  2032. if (!BaseOpS->isIdenticalTo(*BaseOpD))
  2033. return true;
  2034. // Check that the base register is incremented by a constant value for each
  2035. // iteration.
  2036. MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
  2037. if (!Def || !Def->isPHI())
  2038. return true;
  2039. unsigned InitVal = 0;
  2040. unsigned LoopVal = 0;
  2041. getPhiRegs(*Def, BB, InitVal, LoopVal);
  2042. MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
  2043. int D = 0;
  2044. if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
  2045. return true;
  2046. uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
  2047. uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
  2048. // This is the main test, which checks the offset values and the loop
  2049. // increment value to determine if the accesses may be loop carried.
  2050. if (AccessSizeS == MemoryLocation::UnknownSize ||
  2051. AccessSizeD == MemoryLocation::UnknownSize)
  2052. return true;
  2053. if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
  2054. return true;
  2055. return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
  2056. }
  2057. void SwingSchedulerDAG::postprocessDAG() {
  2058. for (auto &M : Mutations)
  2059. M->apply(this);
  2060. }
  2061. /// Try to schedule the node at the specified StartCycle and continue
  2062. /// until the node is schedule or the EndCycle is reached. This function
  2063. /// returns true if the node is scheduled. This routine may search either
  2064. /// forward or backward for a place to insert the instruction based upon
  2065. /// the relative values of StartCycle and EndCycle.
  2066. bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
  2067. bool forward = true;
  2068. LLVM_DEBUG({
  2069. dbgs() << "Trying to insert node between " << StartCycle << " and "
  2070. << EndCycle << " II: " << II << "\n";
  2071. });
  2072. if (StartCycle > EndCycle)
  2073. forward = false;
  2074. // The terminating condition depends on the direction.
  2075. int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
  2076. for (int curCycle = StartCycle; curCycle != termCycle;
  2077. forward ? ++curCycle : --curCycle) {
  2078. // Add the already scheduled instructions at the specified cycle to the
  2079. // DFA.
  2080. ProcItinResources.clearResources();
  2081. for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
  2082. checkCycle <= LastCycle; checkCycle += II) {
  2083. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
  2084. for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
  2085. E = cycleInstrs.end();
  2086. I != E; ++I) {
  2087. if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
  2088. continue;
  2089. assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) &&
  2090. "These instructions have already been scheduled.");
  2091. ProcItinResources.reserveResources(*(*I)->getInstr());
  2092. }
  2093. }
  2094. if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
  2095. ProcItinResources.canReserveResources(*SU->getInstr())) {
  2096. LLVM_DEBUG({
  2097. dbgs() << "\tinsert at cycle " << curCycle << " ";
  2098. SU->getInstr()->dump();
  2099. });
  2100. ScheduledInstrs[curCycle].push_back(SU);
  2101. InstrToCycle.insert(std::make_pair(SU, curCycle));
  2102. if (curCycle > LastCycle)
  2103. LastCycle = curCycle;
  2104. if (curCycle < FirstCycle)
  2105. FirstCycle = curCycle;
  2106. return true;
  2107. }
  2108. LLVM_DEBUG({
  2109. dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
  2110. SU->getInstr()->dump();
  2111. });
  2112. }
  2113. return false;
  2114. }
  2115. // Return the cycle of the earliest scheduled instruction in the chain.
  2116. int SMSchedule::earliestCycleInChain(const SDep &Dep) {
  2117. SmallPtrSet<SUnit *, 8> Visited;
  2118. SmallVector<SDep, 8> Worklist;
  2119. Worklist.push_back(Dep);
  2120. int EarlyCycle = INT_MAX;
  2121. while (!Worklist.empty()) {
  2122. const SDep &Cur = Worklist.pop_back_val();
  2123. SUnit *PrevSU = Cur.getSUnit();
  2124. if (Visited.count(PrevSU))
  2125. continue;
  2126. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
  2127. if (it == InstrToCycle.end())
  2128. continue;
  2129. EarlyCycle = std::min(EarlyCycle, it->second);
  2130. for (const auto &PI : PrevSU->Preds)
  2131. if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  2132. Worklist.push_back(PI);
  2133. Visited.insert(PrevSU);
  2134. }
  2135. return EarlyCycle;
  2136. }
  2137. // Return the cycle of the latest scheduled instruction in the chain.
  2138. int SMSchedule::latestCycleInChain(const SDep &Dep) {
  2139. SmallPtrSet<SUnit *, 8> Visited;
  2140. SmallVector<SDep, 8> Worklist;
  2141. Worklist.push_back(Dep);
  2142. int LateCycle = INT_MIN;
  2143. while (!Worklist.empty()) {
  2144. const SDep &Cur = Worklist.pop_back_val();
  2145. SUnit *SuccSU = Cur.getSUnit();
  2146. if (Visited.count(SuccSU))
  2147. continue;
  2148. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
  2149. if (it == InstrToCycle.end())
  2150. continue;
  2151. LateCycle = std::max(LateCycle, it->second);
  2152. for (const auto &SI : SuccSU->Succs)
  2153. if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  2154. Worklist.push_back(SI);
  2155. Visited.insert(SuccSU);
  2156. }
  2157. return LateCycle;
  2158. }
  2159. /// If an instruction has a use that spans multiple iterations, then
  2160. /// return true. These instructions are characterized by having a back-ege
  2161. /// to a Phi, which contains a reference to another Phi.
  2162. static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
  2163. for (auto &P : SU->Preds)
  2164. if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
  2165. for (auto &S : P.getSUnit()->Succs)
  2166. if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
  2167. return P.getSUnit();
  2168. return nullptr;
  2169. }
  2170. /// Compute the scheduling start slot for the instruction. The start slot
  2171. /// depends on any predecessor or successor nodes scheduled already.
  2172. void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
  2173. int *MinEnd, int *MaxStart, int II,
  2174. SwingSchedulerDAG *DAG) {
  2175. // Iterate over each instruction that has been scheduled already. The start
  2176. // slot computation depends on whether the previously scheduled instruction
  2177. // is a predecessor or successor of the specified instruction.
  2178. for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
  2179. // Iterate over each instruction in the current cycle.
  2180. for (SUnit *I : getInstructions(cycle)) {
  2181. // Because we're processing a DAG for the dependences, we recognize
  2182. // the back-edge in recurrences by anti dependences.
  2183. for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
  2184. const SDep &Dep = SU->Preds[i];
  2185. if (Dep.getSUnit() == I) {
  2186. if (!DAG->isBackedge(SU, Dep)) {
  2187. int EarlyStart = cycle + Dep.getLatency() -
  2188. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  2189. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  2190. if (DAG->isLoopCarriedDep(SU, Dep, false)) {
  2191. int End = earliestCycleInChain(Dep) + (II - 1);
  2192. *MinEnd = std::min(*MinEnd, End);
  2193. }
  2194. } else {
  2195. int LateStart = cycle - Dep.getLatency() +
  2196. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  2197. *MinLateStart = std::min(*MinLateStart, LateStart);
  2198. }
  2199. }
  2200. // For instruction that requires multiple iterations, make sure that
  2201. // the dependent instruction is not scheduled past the definition.
  2202. SUnit *BE = multipleIterations(I, DAG);
  2203. if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
  2204. !SU->isPred(I))
  2205. *MinLateStart = std::min(*MinLateStart, cycle);
  2206. }
  2207. for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
  2208. if (SU->Succs[i].getSUnit() == I) {
  2209. const SDep &Dep = SU->Succs[i];
  2210. if (!DAG->isBackedge(SU, Dep)) {
  2211. int LateStart = cycle - Dep.getLatency() +
  2212. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  2213. *MinLateStart = std::min(*MinLateStart, LateStart);
  2214. if (DAG->isLoopCarriedDep(SU, Dep)) {
  2215. int Start = latestCycleInChain(Dep) + 1 - II;
  2216. *MaxStart = std::max(*MaxStart, Start);
  2217. }
  2218. } else {
  2219. int EarlyStart = cycle + Dep.getLatency() -
  2220. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  2221. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  2222. }
  2223. }
  2224. }
  2225. }
  2226. }
  2227. }
  2228. /// Order the instructions within a cycle so that the definitions occur
  2229. /// before the uses. Returns true if the instruction is added to the start
  2230. /// of the list, or false if added to the end.
  2231. void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
  2232. std::deque<SUnit *> &Insts) {
  2233. MachineInstr *MI = SU->getInstr();
  2234. bool OrderBeforeUse = false;
  2235. bool OrderAfterDef = false;
  2236. bool OrderBeforeDef = false;
  2237. unsigned MoveDef = 0;
  2238. unsigned MoveUse = 0;
  2239. int StageInst1 = stageScheduled(SU);
  2240. unsigned Pos = 0;
  2241. for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
  2242. ++I, ++Pos) {
  2243. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  2244. MachineOperand &MO = MI->getOperand(i);
  2245. if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
  2246. continue;
  2247. Register Reg = MO.getReg();
  2248. unsigned BasePos, OffsetPos;
  2249. if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  2250. if (MI->getOperand(BasePos).getReg() == Reg)
  2251. if (unsigned NewReg = SSD->getInstrBaseReg(SU))
  2252. Reg = NewReg;
  2253. bool Reads, Writes;
  2254. std::tie(Reads, Writes) =
  2255. (*I)->getInstr()->readsWritesVirtualRegister(Reg);
  2256. if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
  2257. OrderBeforeUse = true;
  2258. if (MoveUse == 0)
  2259. MoveUse = Pos;
  2260. } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
  2261. // Add the instruction after the scheduled instruction.
  2262. OrderAfterDef = true;
  2263. MoveDef = Pos;
  2264. } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
  2265. if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
  2266. OrderBeforeUse = true;
  2267. if (MoveUse == 0)
  2268. MoveUse = Pos;
  2269. } else {
  2270. OrderAfterDef = true;
  2271. MoveDef = Pos;
  2272. }
  2273. } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
  2274. OrderBeforeUse = true;
  2275. if (MoveUse == 0)
  2276. MoveUse = Pos;
  2277. if (MoveUse != 0) {
  2278. OrderAfterDef = true;
  2279. MoveDef = Pos - 1;
  2280. }
  2281. } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
  2282. // Add the instruction before the scheduled instruction.
  2283. OrderBeforeUse = true;
  2284. if (MoveUse == 0)
  2285. MoveUse = Pos;
  2286. } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
  2287. isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
  2288. if (MoveUse == 0) {
  2289. OrderBeforeDef = true;
  2290. MoveUse = Pos;
  2291. }
  2292. }
  2293. }
  2294. // Check for order dependences between instructions. Make sure the source
  2295. // is ordered before the destination.
  2296. for (auto &S : SU->Succs) {
  2297. if (S.getSUnit() != *I)
  2298. continue;
  2299. if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  2300. OrderBeforeUse = true;
  2301. if (Pos < MoveUse)
  2302. MoveUse = Pos;
  2303. }
  2304. // We did not handle HW dependences in previous for loop,
  2305. // and we normally set Latency = 0 for Anti deps,
  2306. // so may have nodes in same cycle with Anti denpendent on HW regs.
  2307. else if (S.getKind() == SDep::Anti && stageScheduled(*I) == StageInst1) {
  2308. OrderBeforeUse = true;
  2309. if ((MoveUse == 0) || (Pos < MoveUse))
  2310. MoveUse = Pos;
  2311. }
  2312. }
  2313. for (auto &P : SU->Preds) {
  2314. if (P.getSUnit() != *I)
  2315. continue;
  2316. if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  2317. OrderAfterDef = true;
  2318. MoveDef = Pos;
  2319. }
  2320. }
  2321. }
  2322. // A circular dependence.
  2323. if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
  2324. OrderBeforeUse = false;
  2325. // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
  2326. // to a loop-carried dependence.
  2327. if (OrderBeforeDef)
  2328. OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
  2329. // The uncommon case when the instruction order needs to be updated because
  2330. // there is both a use and def.
  2331. if (OrderBeforeUse && OrderAfterDef) {
  2332. SUnit *UseSU = Insts.at(MoveUse);
  2333. SUnit *DefSU = Insts.at(MoveDef);
  2334. if (MoveUse > MoveDef) {
  2335. Insts.erase(Insts.begin() + MoveUse);
  2336. Insts.erase(Insts.begin() + MoveDef);
  2337. } else {
  2338. Insts.erase(Insts.begin() + MoveDef);
  2339. Insts.erase(Insts.begin() + MoveUse);
  2340. }
  2341. orderDependence(SSD, UseSU, Insts);
  2342. orderDependence(SSD, SU, Insts);
  2343. orderDependence(SSD, DefSU, Insts);
  2344. return;
  2345. }
  2346. // Put the new instruction first if there is a use in the list. Otherwise,
  2347. // put it at the end of the list.
  2348. if (OrderBeforeUse)
  2349. Insts.push_front(SU);
  2350. else
  2351. Insts.push_back(SU);
  2352. }
  2353. /// Return true if the scheduled Phi has a loop carried operand.
  2354. bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
  2355. if (!Phi.isPHI())
  2356. return false;
  2357. assert(Phi.isPHI() && "Expecting a Phi.");
  2358. SUnit *DefSU = SSD->getSUnit(&Phi);
  2359. unsigned DefCycle = cycleScheduled(DefSU);
  2360. int DefStage = stageScheduled(DefSU);
  2361. unsigned InitVal = 0;
  2362. unsigned LoopVal = 0;
  2363. getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
  2364. SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
  2365. if (!UseSU)
  2366. return true;
  2367. if (UseSU->getInstr()->isPHI())
  2368. return true;
  2369. unsigned LoopCycle = cycleScheduled(UseSU);
  2370. int LoopStage = stageScheduled(UseSU);
  2371. return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
  2372. }
  2373. /// Return true if the instruction is a definition that is loop carried
  2374. /// and defines the use on the next iteration.
  2375. /// v1 = phi(v2, v3)
  2376. /// (Def) v3 = op v1
  2377. /// (MO) = v1
  2378. /// If MO appears before Def, then then v1 and v3 may get assigned to the same
  2379. /// register.
  2380. bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
  2381. MachineInstr *Def, MachineOperand &MO) {
  2382. if (!MO.isReg())
  2383. return false;
  2384. if (Def->isPHI())
  2385. return false;
  2386. MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
  2387. if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
  2388. return false;
  2389. if (!isLoopCarried(SSD, *Phi))
  2390. return false;
  2391. unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
  2392. for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
  2393. MachineOperand &DMO = Def->getOperand(i);
  2394. if (!DMO.isReg() || !DMO.isDef())
  2395. continue;
  2396. if (DMO.getReg() == LoopReg)
  2397. return true;
  2398. }
  2399. return false;
  2400. }
  2401. // Check if the generated schedule is valid. This function checks if
  2402. // an instruction that uses a physical register is scheduled in a
  2403. // different stage than the definition. The pipeliner does not handle
  2404. // physical register values that may cross a basic block boundary.
  2405. bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
  2406. for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
  2407. SUnit &SU = SSD->SUnits[i];
  2408. if (!SU.hasPhysRegDefs)
  2409. continue;
  2410. int StageDef = stageScheduled(&SU);
  2411. assert(StageDef != -1 && "Instruction should have been scheduled.");
  2412. for (auto &SI : SU.Succs)
  2413. if (SI.isAssignedRegDep())
  2414. if (Register::isPhysicalRegister(SI.getReg()))
  2415. if (stageScheduled(SI.getSUnit()) != StageDef)
  2416. return false;
  2417. }
  2418. return true;
  2419. }
  2420. /// A property of the node order in swing-modulo-scheduling is
  2421. /// that for nodes outside circuits the following holds:
  2422. /// none of them is scheduled after both a successor and a
  2423. /// predecessor.
  2424. /// The method below checks whether the property is met.
  2425. /// If not, debug information is printed and statistics information updated.
  2426. /// Note that we do not use an assert statement.
  2427. /// The reason is that although an invalid node oder may prevent
  2428. /// the pipeliner from finding a pipelined schedule for arbitrary II,
  2429. /// it does not lead to the generation of incorrect code.
  2430. void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
  2431. // a sorted vector that maps each SUnit to its index in the NodeOrder
  2432. typedef std::pair<SUnit *, unsigned> UnitIndex;
  2433. std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
  2434. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
  2435. Indices.push_back(std::make_pair(NodeOrder[i], i));
  2436. auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
  2437. return std::get<0>(i1) < std::get<0>(i2);
  2438. };
  2439. // sort, so that we can perform a binary search
  2440. llvm::sort(Indices, CompareKey);
  2441. bool Valid = true;
  2442. (void)Valid;
  2443. // for each SUnit in the NodeOrder, check whether
  2444. // it appears after both a successor and a predecessor
  2445. // of the SUnit. If this is the case, and the SUnit
  2446. // is not part of circuit, then the NodeOrder is not
  2447. // valid.
  2448. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
  2449. SUnit *SU = NodeOrder[i];
  2450. unsigned Index = i;
  2451. bool PredBefore = false;
  2452. bool SuccBefore = false;
  2453. SUnit *Succ;
  2454. SUnit *Pred;
  2455. (void)Succ;
  2456. (void)Pred;
  2457. for (SDep &PredEdge : SU->Preds) {
  2458. SUnit *PredSU = PredEdge.getSUnit();
  2459. unsigned PredIndex = std::get<1>(
  2460. *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
  2461. if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
  2462. PredBefore = true;
  2463. Pred = PredSU;
  2464. break;
  2465. }
  2466. }
  2467. for (SDep &SuccEdge : SU->Succs) {
  2468. SUnit *SuccSU = SuccEdge.getSUnit();
  2469. // Do not process a boundary node, it was not included in NodeOrder,
  2470. // hence not in Indices either, call to std::lower_bound() below will
  2471. // return Indices.end().
  2472. if (SuccSU->isBoundaryNode())
  2473. continue;
  2474. unsigned SuccIndex = std::get<1>(
  2475. *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
  2476. if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
  2477. SuccBefore = true;
  2478. Succ = SuccSU;
  2479. break;
  2480. }
  2481. }
  2482. if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
  2483. // instructions in circuits are allowed to be scheduled
  2484. // after both a successor and predecessor.
  2485. bool InCircuit = llvm::any_of(
  2486. Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
  2487. if (InCircuit)
  2488. LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
  2489. else {
  2490. Valid = false;
  2491. NumNodeOrderIssues++;
  2492. LLVM_DEBUG(dbgs() << "Predecessor ";);
  2493. }
  2494. LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
  2495. << " are scheduled before node " << SU->NodeNum
  2496. << "\n";);
  2497. }
  2498. }
  2499. LLVM_DEBUG({
  2500. if (!Valid)
  2501. dbgs() << "Invalid node order found!\n";
  2502. });
  2503. }
  2504. /// Attempt to fix the degenerate cases when the instruction serialization
  2505. /// causes the register lifetimes to overlap. For example,
  2506. /// p' = store_pi(p, b)
  2507. /// = load p, offset
  2508. /// In this case p and p' overlap, which means that two registers are needed.
  2509. /// Instead, this function changes the load to use p' and updates the offset.
  2510. void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
  2511. unsigned OverlapReg = 0;
  2512. unsigned NewBaseReg = 0;
  2513. for (SUnit *SU : Instrs) {
  2514. MachineInstr *MI = SU->getInstr();
  2515. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  2516. const MachineOperand &MO = MI->getOperand(i);
  2517. // Look for an instruction that uses p. The instruction occurs in the
  2518. // same cycle but occurs later in the serialized order.
  2519. if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
  2520. // Check that the instruction appears in the InstrChanges structure,
  2521. // which contains instructions that can have the offset updated.
  2522. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  2523. InstrChanges.find(SU);
  2524. if (It != InstrChanges.end()) {
  2525. unsigned BasePos, OffsetPos;
  2526. // Update the base register and adjust the offset.
  2527. if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
  2528. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  2529. NewMI->getOperand(BasePos).setReg(NewBaseReg);
  2530. int64_t NewOffset =
  2531. MI->getOperand(OffsetPos).getImm() - It->second.second;
  2532. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  2533. SU->setInstr(NewMI);
  2534. MISUnitMap[NewMI] = SU;
  2535. NewMIs[MI] = NewMI;
  2536. }
  2537. }
  2538. OverlapReg = 0;
  2539. NewBaseReg = 0;
  2540. break;
  2541. }
  2542. // Look for an instruction of the form p' = op(p), which uses and defines
  2543. // two virtual registers that get allocated to the same physical register.
  2544. unsigned TiedUseIdx = 0;
  2545. if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
  2546. // OverlapReg is p in the example above.
  2547. OverlapReg = MI->getOperand(TiedUseIdx).getReg();
  2548. // NewBaseReg is p' in the example above.
  2549. NewBaseReg = MI->getOperand(i).getReg();
  2550. break;
  2551. }
  2552. }
  2553. }
  2554. }
  2555. /// After the schedule has been formed, call this function to combine
  2556. /// the instructions from the different stages/cycles. That is, this
  2557. /// function creates a schedule that represents a single iteration.
  2558. void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
  2559. // Move all instructions to the first stage from later stages.
  2560. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  2561. for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
  2562. ++stage) {
  2563. std::deque<SUnit *> &cycleInstrs =
  2564. ScheduledInstrs[cycle + (stage * InitiationInterval)];
  2565. for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
  2566. E = cycleInstrs.rend();
  2567. I != E; ++I)
  2568. ScheduledInstrs[cycle].push_front(*I);
  2569. }
  2570. }
  2571. // Erase all the elements in the later stages. Only one iteration should
  2572. // remain in the scheduled list, and it contains all the instructions.
  2573. for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
  2574. ScheduledInstrs.erase(cycle);
  2575. // Change the registers in instruction as specified in the InstrChanges
  2576. // map. We need to use the new registers to create the correct order.
  2577. for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
  2578. SUnit *SU = &SSD->SUnits[i];
  2579. SSD->applyInstrChange(SU->getInstr(), *this);
  2580. }
  2581. // Reorder the instructions in each cycle to fix and improve the
  2582. // generated code.
  2583. for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
  2584. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
  2585. std::deque<SUnit *> newOrderPhi;
  2586. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  2587. SUnit *SU = cycleInstrs[i];
  2588. if (SU->getInstr()->isPHI())
  2589. newOrderPhi.push_back(SU);
  2590. }
  2591. std::deque<SUnit *> newOrderI;
  2592. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  2593. SUnit *SU = cycleInstrs[i];
  2594. if (!SU->getInstr()->isPHI())
  2595. orderDependence(SSD, SU, newOrderI);
  2596. }
  2597. // Replace the old order with the new order.
  2598. cycleInstrs.swap(newOrderPhi);
  2599. cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
  2600. SSD->fixupRegisterOverlaps(cycleInstrs);
  2601. }
  2602. LLVM_DEBUG(dump(););
  2603. }
  2604. void NodeSet::print(raw_ostream &os) const {
  2605. os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
  2606. << " depth " << MaxDepth << " col " << Colocate << "\n";
  2607. for (const auto &I : Nodes)
  2608. os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
  2609. os << "\n";
  2610. }
  2611. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2612. /// Print the schedule information to the given output.
  2613. void SMSchedule::print(raw_ostream &os) const {
  2614. // Iterate over each cycle.
  2615. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  2616. // Iterate over each instruction in the cycle.
  2617. const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
  2618. for (SUnit *CI : cycleInstrs->second) {
  2619. os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
  2620. os << "(" << CI->NodeNum << ") ";
  2621. CI->getInstr()->print(os);
  2622. os << "\n";
  2623. }
  2624. }
  2625. }
  2626. /// Utility function used for debugging to print the schedule.
  2627. LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
  2628. LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
  2629. #endif
  2630. void ResourceManager::initProcResourceVectors(
  2631. const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
  2632. unsigned ProcResourceID = 0;
  2633. // We currently limit the resource kinds to 64 and below so that we can use
  2634. // uint64_t for Masks
  2635. assert(SM.getNumProcResourceKinds() < 64 &&
  2636. "Too many kinds of resources, unsupported");
  2637. // Create a unique bitmask for every processor resource unit.
  2638. // Skip resource at index 0, since it always references 'InvalidUnit'.
  2639. Masks.resize(SM.getNumProcResourceKinds());
  2640. for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
  2641. const MCProcResourceDesc &Desc = *SM.getProcResource(I);
  2642. if (Desc.SubUnitsIdxBegin)
  2643. continue;
  2644. Masks[I] = 1ULL << ProcResourceID;
  2645. ProcResourceID++;
  2646. }
  2647. // Create a unique bitmask for every processor resource group.
  2648. for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
  2649. const MCProcResourceDesc &Desc = *SM.getProcResource(I);
  2650. if (!Desc.SubUnitsIdxBegin)
  2651. continue;
  2652. Masks[I] = 1ULL << ProcResourceID;
  2653. for (unsigned U = 0; U < Desc.NumUnits; ++U)
  2654. Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
  2655. ProcResourceID++;
  2656. }
  2657. LLVM_DEBUG({
  2658. if (SwpShowResMask) {
  2659. dbgs() << "ProcResourceDesc:\n";
  2660. for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
  2661. const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
  2662. dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
  2663. ProcResource->Name, I, Masks[I],
  2664. ProcResource->NumUnits);
  2665. }
  2666. dbgs() << " -----------------\n";
  2667. }
  2668. });
  2669. }
  2670. bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
  2671. LLVM_DEBUG({
  2672. if (SwpDebugResource)
  2673. dbgs() << "canReserveResources:\n";
  2674. });
  2675. if (UseDFA)
  2676. return DFAResources->canReserveResources(MID);
  2677. unsigned InsnClass = MID->getSchedClass();
  2678. const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
  2679. if (!SCDesc->isValid()) {
  2680. LLVM_DEBUG({
  2681. dbgs() << "No valid Schedule Class Desc for schedClass!\n";
  2682. dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
  2683. });
  2684. return true;
  2685. }
  2686. const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
  2687. const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
  2688. for (; I != E; ++I) {
  2689. if (!I->Cycles)
  2690. continue;
  2691. const MCProcResourceDesc *ProcResource =
  2692. SM.getProcResource(I->ProcResourceIdx);
  2693. unsigned NumUnits = ProcResource->NumUnits;
  2694. LLVM_DEBUG({
  2695. if (SwpDebugResource)
  2696. dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
  2697. ProcResource->Name, I->ProcResourceIdx,
  2698. ProcResourceCount[I->ProcResourceIdx], NumUnits,
  2699. I->Cycles);
  2700. });
  2701. if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
  2702. return false;
  2703. }
  2704. LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
  2705. return true;
  2706. }
  2707. void ResourceManager::reserveResources(const MCInstrDesc *MID) {
  2708. LLVM_DEBUG({
  2709. if (SwpDebugResource)
  2710. dbgs() << "reserveResources:\n";
  2711. });
  2712. if (UseDFA)
  2713. return DFAResources->reserveResources(MID);
  2714. unsigned InsnClass = MID->getSchedClass();
  2715. const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
  2716. if (!SCDesc->isValid()) {
  2717. LLVM_DEBUG({
  2718. dbgs() << "No valid Schedule Class Desc for schedClass!\n";
  2719. dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
  2720. });
  2721. return;
  2722. }
  2723. for (const MCWriteProcResEntry &PRE :
  2724. make_range(STI->getWriteProcResBegin(SCDesc),
  2725. STI->getWriteProcResEnd(SCDesc))) {
  2726. if (!PRE.Cycles)
  2727. continue;
  2728. ++ProcResourceCount[PRE.ProcResourceIdx];
  2729. LLVM_DEBUG({
  2730. if (SwpDebugResource) {
  2731. const MCProcResourceDesc *ProcResource =
  2732. SM.getProcResource(PRE.ProcResourceIdx);
  2733. dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
  2734. ProcResource->Name, PRE.ProcResourceIdx,
  2735. ProcResourceCount[PRE.ProcResourceIdx],
  2736. ProcResource->NumUnits, PRE.Cycles);
  2737. }
  2738. });
  2739. }
  2740. LLVM_DEBUG({
  2741. if (SwpDebugResource)
  2742. dbgs() << "reserveResources: done!\n\n";
  2743. });
  2744. }
  2745. bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
  2746. return canReserveResources(&MI.getDesc());
  2747. }
  2748. void ResourceManager::reserveResources(const MachineInstr &MI) {
  2749. return reserveResources(&MI.getDesc());
  2750. }
  2751. void ResourceManager::clearResources() {
  2752. if (UseDFA)
  2753. return DFAResources->clearResources();
  2754. std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
  2755. }