MachinePipeliner.cpp 109 KB

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