MachinePipeliner.cpp 116 KB

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