MachinePipeliner.cpp 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087
  1. //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
  10. //
  11. // This SMS implementation is a target-independent back-end pass. When enabled,
  12. // the pass runs just prior to the register allocation pass, while the machine
  13. // IR is in SSA form. If software pipelining is successful, then the original
  14. // loop is replaced by the optimized loop. The optimized loop contains one or
  15. // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
  16. // the instructions cannot be scheduled in a given MII, we increase the MII by
  17. // one and try again.
  18. //
  19. // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
  20. // represent loop carried dependences in the DAG as order edges to the Phi
  21. // nodes. We also perform several passes over the DAG to eliminate unnecessary
  22. // edges that inhibit the ability to pipeline. The implementation uses the
  23. // DFAPacketizer class to compute the minimum initiation interval and the check
  24. // where an instruction may be inserted in the pipelined schedule.
  25. //
  26. // In order for the SMS pass to work, several target specific hooks need to be
  27. // implemented to get information about the loop structure and to rewrite
  28. // instructions.
  29. //
  30. //===----------------------------------------------------------------------===//
  31. #include "llvm/ADT/ArrayRef.h"
  32. #include "llvm/ADT/BitVector.h"
  33. #include "llvm/ADT/DenseMap.h"
  34. #include "llvm/ADT/MapVector.h"
  35. #include "llvm/ADT/PriorityQueue.h"
  36. #include "llvm/ADT/SetVector.h"
  37. #include "llvm/ADT/SmallPtrSet.h"
  38. #include "llvm/ADT/SmallSet.h"
  39. #include "llvm/ADT/SmallVector.h"
  40. #include "llvm/ADT/Statistic.h"
  41. #include "llvm/ADT/iterator_range.h"
  42. #include "llvm/Analysis/AliasAnalysis.h"
  43. #include "llvm/Analysis/MemoryLocation.h"
  44. #include "llvm/Analysis/ValueTracking.h"
  45. #include "llvm/CodeGen/DFAPacketizer.h"
  46. #include "llvm/CodeGen/LiveIntervals.h"
  47. #include "llvm/CodeGen/MachineBasicBlock.h"
  48. #include "llvm/CodeGen/MachineDominators.h"
  49. #include "llvm/CodeGen/MachineFunction.h"
  50. #include "llvm/CodeGen/MachineFunctionPass.h"
  51. #include "llvm/CodeGen/MachineInstr.h"
  52. #include "llvm/CodeGen/MachineInstrBuilder.h"
  53. #include "llvm/CodeGen/MachineLoopInfo.h"
  54. #include "llvm/CodeGen/MachineMemOperand.h"
  55. #include "llvm/CodeGen/MachineOperand.h"
  56. #include "llvm/CodeGen/MachinePipeliner.h"
  57. #include "llvm/CodeGen/MachineRegisterInfo.h"
  58. #include "llvm/CodeGen/RegisterPressure.h"
  59. #include "llvm/CodeGen/ScheduleDAG.h"
  60. #include "llvm/CodeGen/ScheduleDAGMutation.h"
  61. #include "llvm/CodeGen/TargetOpcodes.h"
  62. #include "llvm/CodeGen/TargetRegisterInfo.h"
  63. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  64. #include "llvm/Config/llvm-config.h"
  65. #include "llvm/IR/Attributes.h"
  66. #include "llvm/IR/DebugLoc.h"
  67. #include "llvm/IR/Function.h"
  68. #include "llvm/MC/LaneBitmask.h"
  69. #include "llvm/MC/MCInstrDesc.h"
  70. #include "llvm/MC/MCInstrItineraries.h"
  71. #include "llvm/MC/MCRegisterInfo.h"
  72. #include "llvm/Pass.h"
  73. #include "llvm/Support/CommandLine.h"
  74. #include "llvm/Support/Compiler.h"
  75. #include "llvm/Support/Debug.h"
  76. #include "llvm/Support/MathExtras.h"
  77. #include "llvm/Support/raw_ostream.h"
  78. #include <algorithm>
  79. #include <cassert>
  80. #include <climits>
  81. #include <cstdint>
  82. #include <deque>
  83. #include <functional>
  84. #include <iterator>
  85. #include <map>
  86. #include <memory>
  87. #include <tuple>
  88. #include <utility>
  89. #include <vector>
  90. using namespace llvm;
  91. #define DEBUG_TYPE "pipeliner"
  92. STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
  93. STATISTIC(NumPipelined, "Number of loops software pipelined");
  94. STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
  95. STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
  96. STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
  97. STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
  98. STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
  99. STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
  100. STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
  101. STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
  102. STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
  103. /// A command line option to turn software pipelining on or off.
  104. static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
  105. cl::ZeroOrMore,
  106. cl::desc("Enable Software Pipelining"));
  107. /// A command line option to enable SWP at -Os.
  108. static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
  109. cl::desc("Enable SWP at Os."), cl::Hidden,
  110. cl::init(false));
  111. /// A command line argument to limit minimum initial interval for pipelining.
  112. static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
  113. cl::desc("Size limit for the MII."),
  114. cl::Hidden, cl::init(27));
  115. /// A command line argument to limit the number of stages in the pipeline.
  116. static cl::opt<int>
  117. SwpMaxStages("pipeliner-max-stages",
  118. cl::desc("Maximum stages allowed in the generated scheduled."),
  119. cl::Hidden, cl::init(3));
  120. /// A command line option to disable the pruning of chain dependences due to
  121. /// an unrelated Phi.
  122. static cl::opt<bool>
  123. SwpPruneDeps("pipeliner-prune-deps",
  124. cl::desc("Prune dependences between unrelated Phi nodes."),
  125. cl::Hidden, cl::init(true));
  126. /// A command line option to disable the pruning of loop carried order
  127. /// dependences.
  128. static cl::opt<bool>
  129. SwpPruneLoopCarried("pipeliner-prune-loop-carried",
  130. cl::desc("Prune loop carried order dependences."),
  131. cl::Hidden, cl::init(true));
  132. #ifndef NDEBUG
  133. static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
  134. #endif
  135. static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
  136. cl::ReallyHidden, cl::init(false),
  137. cl::ZeroOrMore, cl::desc("Ignore RecMII"));
  138. static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
  139. cl::init(false));
  140. static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
  141. cl::init(false));
  142. namespace llvm {
  143. // A command line option to enable the CopyToPhi DAG mutation.
  144. cl::opt<bool>
  145. SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
  146. cl::init(true), cl::ZeroOrMore,
  147. cl::desc("Enable CopyToPhi DAG Mutation"));
  148. } // end namespace llvm
  149. unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
  150. char MachinePipeliner::ID = 0;
  151. #ifndef NDEBUG
  152. int MachinePipeliner::NumTries = 0;
  153. #endif
  154. char &llvm::MachinePipelinerID = MachinePipeliner::ID;
  155. INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
  156. "Modulo Software Pipelining", false, false)
  157. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  158. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  159. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  160. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  161. INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
  162. "Modulo Software Pipelining", false, false)
  163. /// The "main" function for implementing Swing Modulo Scheduling.
  164. bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
  165. if (skipFunction(mf.getFunction()))
  166. return false;
  167. if (!EnableSWP)
  168. return false;
  169. if (mf.getFunction().getAttributes().hasAttribute(
  170. AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
  171. !EnableSWPOptSize.getPosition())
  172. return false;
  173. if (!mf.getSubtarget().enableMachinePipeliner())
  174. return false;
  175. // Cannot pipeline loops without instruction itineraries if we are using
  176. // DFA for the pipeliner.
  177. if (mf.getSubtarget().useDFAforSMS() &&
  178. (!mf.getSubtarget().getInstrItineraryData() ||
  179. mf.getSubtarget().getInstrItineraryData()->isEmpty()))
  180. return false;
  181. MF = &mf;
  182. MLI = &getAnalysis<MachineLoopInfo>();
  183. MDT = &getAnalysis<MachineDominatorTree>();
  184. TII = MF->getSubtarget().getInstrInfo();
  185. RegClassInfo.runOnMachineFunction(*MF);
  186. for (auto &L : *MLI)
  187. scheduleLoop(*L);
  188. return false;
  189. }
  190. /// Attempt to perform the SMS algorithm on the specified loop. This function is
  191. /// the main entry point for the algorithm. The function identifies candidate
  192. /// loops, calculates the minimum initiation interval, and attempts to schedule
  193. /// the loop.
  194. bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
  195. bool Changed = false;
  196. for (auto &InnerLoop : L)
  197. Changed |= scheduleLoop(*InnerLoop);
  198. #ifndef NDEBUG
  199. // Stop trying after reaching the limit (if any).
  200. int Limit = SwpLoopLimit;
  201. if (Limit >= 0) {
  202. if (NumTries >= SwpLoopLimit)
  203. return Changed;
  204. NumTries++;
  205. }
  206. #endif
  207. setPragmaPipelineOptions(L);
  208. if (!canPipelineLoop(L)) {
  209. LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
  210. return Changed;
  211. }
  212. ++NumTrytoPipeline;
  213. Changed = swingModuloScheduler(L);
  214. return Changed;
  215. }
  216. void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
  217. MachineBasicBlock *LBLK = L.getTopBlock();
  218. if (LBLK == nullptr)
  219. return;
  220. const BasicBlock *BBLK = LBLK->getBasicBlock();
  221. if (BBLK == nullptr)
  222. return;
  223. const Instruction *TI = BBLK->getTerminator();
  224. if (TI == nullptr)
  225. return;
  226. MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
  227. if (LoopID == nullptr)
  228. return;
  229. assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
  230. assert(LoopID->getOperand(0) == LoopID && "invalid loop");
  231. for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
  232. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  233. if (MD == nullptr)
  234. continue;
  235. MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  236. if (S == nullptr)
  237. continue;
  238. if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
  239. assert(MD->getNumOperands() == 2 &&
  240. "Pipeline initiation interval hint metadata should have two operands.");
  241. II_setByPragma =
  242. mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
  243. assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
  244. } else if (S->getString() == "llvm.loop.pipeline.disable") {
  245. disabledByPragma = true;
  246. }
  247. }
  248. }
  249. /// Return true if the loop can be software pipelined. The algorithm is
  250. /// restricted to loops with a single basic block. Make sure that the
  251. /// branch in the loop can be analyzed.
  252. bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
  253. if (L.getNumBlocks() != 1)
  254. return false;
  255. if (disabledByPragma)
  256. return false;
  257. // Check if the branch can't be understood because we can't do pipelining
  258. // if that's the case.
  259. LI.TBB = nullptr;
  260. LI.FBB = nullptr;
  261. LI.BrCond.clear();
  262. if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
  263. LLVM_DEBUG(
  264. dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n");
  265. NumFailBranch++;
  266. return false;
  267. }
  268. LI.LoopInductionVar = nullptr;
  269. LI.LoopCompare = nullptr;
  270. if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare)) {
  271. LLVM_DEBUG(
  272. dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n");
  273. NumFailLoop++;
  274. return false;
  275. }
  276. if (!L.getLoopPreheader()) {
  277. LLVM_DEBUG(
  278. dbgs() << "Preheader not found, can NOT pipeline current Loop\n");
  279. NumFailPreheader++;
  280. return false;
  281. }
  282. // Remove any subregisters from inputs to phi nodes.
  283. preprocessPhiNodes(*L.getHeader());
  284. return true;
  285. }
  286. void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
  287. MachineRegisterInfo &MRI = MF->getRegInfo();
  288. SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
  289. for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
  290. MachineOperand &DefOp = PI.getOperand(0);
  291. assert(DefOp.getSubReg() == 0);
  292. auto *RC = MRI.getRegClass(DefOp.getReg());
  293. for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
  294. MachineOperand &RegOp = PI.getOperand(i);
  295. if (RegOp.getSubReg() == 0)
  296. continue;
  297. // If the operand uses a subregister, replace it with a new register
  298. // without subregisters, and generate a copy to the new register.
  299. unsigned NewReg = MRI.createVirtualRegister(RC);
  300. MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
  301. MachineBasicBlock::iterator At = PredB.getFirstTerminator();
  302. const DebugLoc &DL = PredB.findDebugLoc(At);
  303. auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
  304. .addReg(RegOp.getReg(), getRegState(RegOp),
  305. RegOp.getSubReg());
  306. Slots.insertMachineInstrInMaps(*Copy);
  307. RegOp.setReg(NewReg);
  308. RegOp.setSubReg(0);
  309. }
  310. }
  311. }
  312. /// The SMS algorithm consists of the following main steps:
  313. /// 1. Computation and analysis of the dependence graph.
  314. /// 2. Ordering of the nodes (instructions).
  315. /// 3. Attempt to Schedule the loop.
  316. bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
  317. assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
  318. SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
  319. II_setByPragma);
  320. MachineBasicBlock *MBB = L.getHeader();
  321. // The kernel should not include any terminator instructions. These
  322. // will be added back later.
  323. SMS.startBlock(MBB);
  324. // Compute the number of 'real' instructions in the basic block by
  325. // ignoring terminators.
  326. unsigned size = MBB->size();
  327. for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
  328. E = MBB->instr_end();
  329. I != E; ++I, --size)
  330. ;
  331. SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
  332. SMS.schedule();
  333. SMS.exitRegion();
  334. SMS.finishBlock();
  335. return SMS.hasNewSchedule();
  336. }
  337. void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
  338. if (II_setByPragma > 0)
  339. MII = II_setByPragma;
  340. else
  341. MII = std::max(ResMII, RecMII);
  342. }
  343. void SwingSchedulerDAG::setMAX_II() {
  344. if (II_setByPragma > 0)
  345. MAX_II = II_setByPragma;
  346. else
  347. MAX_II = MII + 10;
  348. }
  349. /// We override the schedule function in ScheduleDAGInstrs to implement the
  350. /// scheduling part of the Swing Modulo Scheduling algorithm.
  351. void SwingSchedulerDAG::schedule() {
  352. AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
  353. buildSchedGraph(AA);
  354. addLoopCarriedDependences(AA);
  355. updatePhiDependences();
  356. Topo.InitDAGTopologicalSorting();
  357. changeDependences();
  358. postprocessDAG();
  359. LLVM_DEBUG(dump());
  360. NodeSetType NodeSets;
  361. findCircuits(NodeSets);
  362. NodeSetType Circuits = NodeSets;
  363. // Calculate the MII.
  364. unsigned ResMII = calculateResMII();
  365. unsigned RecMII = calculateRecMII(NodeSets);
  366. fuseRecs(NodeSets);
  367. // This flag is used for testing and can cause correctness problems.
  368. if (SwpIgnoreRecMII)
  369. RecMII = 0;
  370. setMII(ResMII, RecMII);
  371. setMAX_II();
  372. LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
  373. << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
  374. // Can't schedule a loop without a valid MII.
  375. if (MII == 0) {
  376. LLVM_DEBUG(
  377. dbgs()
  378. << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
  379. NumFailZeroMII++;
  380. return;
  381. }
  382. // Don't pipeline large loops.
  383. if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
  384. LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
  385. << ", we don't pipleline large loops\n");
  386. NumFailLargeMaxMII++;
  387. return;
  388. }
  389. computeNodeFunctions(NodeSets);
  390. registerPressureFilter(NodeSets);
  391. colocateNodeSets(NodeSets);
  392. checkNodeSets(NodeSets);
  393. LLVM_DEBUG({
  394. for (auto &I : NodeSets) {
  395. dbgs() << " Rec NodeSet ";
  396. I.dump();
  397. }
  398. });
  399. llvm::stable_sort(NodeSets, std::greater<NodeSet>());
  400. groupRemainingNodes(NodeSets);
  401. removeDuplicateNodes(NodeSets);
  402. LLVM_DEBUG({
  403. for (auto &I : NodeSets) {
  404. dbgs() << " NodeSet ";
  405. I.dump();
  406. }
  407. });
  408. computeNodeOrder(NodeSets);
  409. // check for node order issues
  410. checkValidNodeOrder(Circuits);
  411. SMSchedule Schedule(Pass.MF);
  412. Scheduled = schedulePipeline(Schedule);
  413. if (!Scheduled){
  414. LLVM_DEBUG(dbgs() << "No schedule found, return\n");
  415. NumFailNoSchedule++;
  416. return;
  417. }
  418. unsigned numStages = Schedule.getMaxStageCount();
  419. // No need to generate pipeline if there are no overlapped iterations.
  420. if (numStages == 0) {
  421. LLVM_DEBUG(
  422. dbgs() << "No overlapped iterations, no need to generate pipeline\n");
  423. NumFailZeroStage++;
  424. return;
  425. }
  426. // Check that the maximum stage count is less than user-defined limit.
  427. if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
  428. LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
  429. << " : too many stages, abort\n");
  430. NumFailLargeMaxStage++;
  431. return;
  432. }
  433. generatePipelinedLoop(Schedule);
  434. ++NumPipelined;
  435. }
  436. /// Clean up after the software pipeliner runs.
  437. void SwingSchedulerDAG::finishBlock() {
  438. for (MachineInstr *I : NewMIs)
  439. MF.DeleteMachineInstr(I);
  440. NewMIs.clear();
  441. // Call the superclass.
  442. ScheduleDAGInstrs::finishBlock();
  443. }
  444. /// Return the register values for the operands of a Phi instruction.
  445. /// This function assume the instruction is a Phi.
  446. static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
  447. unsigned &InitVal, unsigned &LoopVal) {
  448. assert(Phi.isPHI() && "Expecting a Phi.");
  449. InitVal = 0;
  450. LoopVal = 0;
  451. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  452. if (Phi.getOperand(i + 1).getMBB() != Loop)
  453. InitVal = Phi.getOperand(i).getReg();
  454. else
  455. LoopVal = Phi.getOperand(i).getReg();
  456. assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
  457. }
  458. /// Return the Phi register value that comes from the incoming block.
  459. static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
  460. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  461. if (Phi.getOperand(i + 1).getMBB() != LoopBB)
  462. return Phi.getOperand(i).getReg();
  463. return 0;
  464. }
  465. /// Return the Phi register value that comes the loop block.
  466. static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
  467. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  468. if (Phi.getOperand(i + 1).getMBB() == LoopBB)
  469. return Phi.getOperand(i).getReg();
  470. return 0;
  471. }
  472. /// Return true if SUb can be reached from SUa following the chain edges.
  473. static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
  474. SmallPtrSet<SUnit *, 8> Visited;
  475. SmallVector<SUnit *, 8> Worklist;
  476. Worklist.push_back(SUa);
  477. while (!Worklist.empty()) {
  478. const SUnit *SU = Worklist.pop_back_val();
  479. for (auto &SI : SU->Succs) {
  480. SUnit *SuccSU = SI.getSUnit();
  481. if (SI.getKind() == SDep::Order) {
  482. if (Visited.count(SuccSU))
  483. continue;
  484. if (SuccSU == SUb)
  485. return true;
  486. Worklist.push_back(SuccSU);
  487. Visited.insert(SuccSU);
  488. }
  489. }
  490. }
  491. return false;
  492. }
  493. /// Return true if the instruction causes a chain between memory
  494. /// references before and after it.
  495. static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
  496. return MI.isCall() || MI.mayRaiseFPException() ||
  497. MI.hasUnmodeledSideEffects() ||
  498. (MI.hasOrderedMemoryRef() &&
  499. (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
  500. }
  501. /// Return the underlying objects for the memory references of an instruction.
  502. /// This function calls the code in ValueTracking, but first checks that the
  503. /// instruction has a memory operand.
  504. static void getUnderlyingObjects(const MachineInstr *MI,
  505. SmallVectorImpl<const Value *> &Objs,
  506. const DataLayout &DL) {
  507. if (!MI->hasOneMemOperand())
  508. return;
  509. MachineMemOperand *MM = *MI->memoperands_begin();
  510. if (!MM->getValue())
  511. return;
  512. GetUnderlyingObjects(MM->getValue(), Objs, DL);
  513. for (const Value *V : Objs) {
  514. if (!isIdentifiedObject(V)) {
  515. Objs.clear();
  516. return;
  517. }
  518. Objs.push_back(V);
  519. }
  520. }
  521. /// Add a chain edge between a load and store if the store can be an
  522. /// alias of the load on a subsequent iteration, i.e., a loop carried
  523. /// dependence. This code is very similar to the code in ScheduleDAGInstrs
  524. /// but that code doesn't create loop carried dependences.
  525. void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
  526. MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
  527. Value *UnknownValue =
  528. UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
  529. for (auto &SU : SUnits) {
  530. MachineInstr &MI = *SU.getInstr();
  531. if (isDependenceBarrier(MI, AA))
  532. PendingLoads.clear();
  533. else if (MI.mayLoad()) {
  534. SmallVector<const Value *, 4> Objs;
  535. getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
  536. if (Objs.empty())
  537. Objs.push_back(UnknownValue);
  538. for (auto V : Objs) {
  539. SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
  540. SUs.push_back(&SU);
  541. }
  542. } else if (MI.mayStore()) {
  543. SmallVector<const Value *, 4> Objs;
  544. getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
  545. if (Objs.empty())
  546. Objs.push_back(UnknownValue);
  547. for (auto V : Objs) {
  548. MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
  549. PendingLoads.find(V);
  550. if (I == PendingLoads.end())
  551. continue;
  552. for (auto Load : I->second) {
  553. if (isSuccOrder(Load, &SU))
  554. continue;
  555. MachineInstr &LdMI = *Load->getInstr();
  556. // First, perform the cheaper check that compares the base register.
  557. // If they are the same and the load offset is less than the store
  558. // offset, then mark the dependence as loop carried potentially.
  559. const MachineOperand *BaseOp1, *BaseOp2;
  560. int64_t Offset1, Offset2;
  561. if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1, TRI) &&
  562. TII->getMemOperandWithOffset(MI, BaseOp2, Offset2, TRI)) {
  563. if (BaseOp1->isIdenticalTo(*BaseOp2) &&
  564. (int)Offset1 < (int)Offset2) {
  565. assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
  566. "What happened to the chain edge?");
  567. SDep Dep(Load, SDep::Barrier);
  568. Dep.setLatency(1);
  569. SU.addPred(Dep);
  570. continue;
  571. }
  572. }
  573. // Second, the more expensive check that uses alias analysis on the
  574. // base registers. If they alias, and the load offset is less than
  575. // the store offset, the mark the dependence as loop carried.
  576. if (!AA) {
  577. SDep Dep(Load, SDep::Barrier);
  578. Dep.setLatency(1);
  579. SU.addPred(Dep);
  580. continue;
  581. }
  582. MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
  583. MachineMemOperand *MMO2 = *MI.memoperands_begin();
  584. if (!MMO1->getValue() || !MMO2->getValue()) {
  585. SDep Dep(Load, SDep::Barrier);
  586. Dep.setLatency(1);
  587. SU.addPred(Dep);
  588. continue;
  589. }
  590. if (MMO1->getValue() == MMO2->getValue() &&
  591. MMO1->getOffset() <= MMO2->getOffset()) {
  592. SDep Dep(Load, SDep::Barrier);
  593. Dep.setLatency(1);
  594. SU.addPred(Dep);
  595. continue;
  596. }
  597. AliasResult AAResult = AA->alias(
  598. MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
  599. MMO1->getAAInfo()),
  600. MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
  601. MMO2->getAAInfo()));
  602. if (AAResult != NoAlias) {
  603. SDep Dep(Load, SDep::Barrier);
  604. Dep.setLatency(1);
  605. SU.addPred(Dep);
  606. }
  607. }
  608. }
  609. }
  610. }
  611. }
  612. /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
  613. /// processes dependences for PHIs. This function adds true dependences
  614. /// from a PHI to a use, and a loop carried dependence from the use to the
  615. /// PHI. The loop carried dependence is represented as an anti dependence
  616. /// edge. This function also removes chain dependences between unrelated
  617. /// PHIs.
  618. void SwingSchedulerDAG::updatePhiDependences() {
  619. SmallVector<SDep, 4> RemoveDeps;
  620. const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
  621. // Iterate over each DAG node.
  622. for (SUnit &I : SUnits) {
  623. RemoveDeps.clear();
  624. // Set to true if the instruction has an operand defined by a Phi.
  625. unsigned HasPhiUse = 0;
  626. unsigned HasPhiDef = 0;
  627. MachineInstr *MI = I.getInstr();
  628. // Iterate over each operand, and we process the definitions.
  629. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  630. MOE = MI->operands_end();
  631. MOI != MOE; ++MOI) {
  632. if (!MOI->isReg())
  633. continue;
  634. unsigned Reg = MOI->getReg();
  635. if (MOI->isDef()) {
  636. // If the register is used by a Phi, then create an anti dependence.
  637. for (MachineRegisterInfo::use_instr_iterator
  638. UI = MRI.use_instr_begin(Reg),
  639. UE = MRI.use_instr_end();
  640. UI != UE; ++UI) {
  641. MachineInstr *UseMI = &*UI;
  642. SUnit *SU = getSUnit(UseMI);
  643. if (SU != nullptr && UseMI->isPHI()) {
  644. if (!MI->isPHI()) {
  645. SDep Dep(SU, SDep::Anti, Reg);
  646. Dep.setLatency(1);
  647. I.addPred(Dep);
  648. } else {
  649. HasPhiDef = Reg;
  650. // Add a chain edge to a dependent Phi that isn't an existing
  651. // predecessor.
  652. if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
  653. I.addPred(SDep(SU, SDep::Barrier));
  654. }
  655. }
  656. }
  657. } else if (MOI->isUse()) {
  658. // If the register is defined by a Phi, then create a true dependence.
  659. MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
  660. if (DefMI == nullptr)
  661. continue;
  662. SUnit *SU = getSUnit(DefMI);
  663. if (SU != nullptr && DefMI->isPHI()) {
  664. if (!MI->isPHI()) {
  665. SDep Dep(SU, SDep::Data, Reg);
  666. Dep.setLatency(0);
  667. ST.adjustSchedDependency(SU, &I, Dep);
  668. I.addPred(Dep);
  669. } else {
  670. HasPhiUse = Reg;
  671. // Add a chain edge to a dependent Phi that isn't an existing
  672. // predecessor.
  673. if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
  674. I.addPred(SDep(SU, SDep::Barrier));
  675. }
  676. }
  677. }
  678. }
  679. // Remove order dependences from an unrelated Phi.
  680. if (!SwpPruneDeps)
  681. continue;
  682. for (auto &PI : I.Preds) {
  683. MachineInstr *PMI = PI.getSUnit()->getInstr();
  684. if (PMI->isPHI() && PI.getKind() == SDep::Order) {
  685. if (I.getInstr()->isPHI()) {
  686. if (PMI->getOperand(0).getReg() == HasPhiUse)
  687. continue;
  688. if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
  689. continue;
  690. }
  691. RemoveDeps.push_back(PI);
  692. }
  693. }
  694. for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
  695. I.removePred(RemoveDeps[i]);
  696. }
  697. }
  698. /// Iterate over each DAG node and see if we can change any dependences
  699. /// in order to reduce the recurrence MII.
  700. void SwingSchedulerDAG::changeDependences() {
  701. // See if an instruction can use a value from the previous iteration.
  702. // If so, we update the base and offset of the instruction and change
  703. // the dependences.
  704. for (SUnit &I : SUnits) {
  705. unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
  706. int64_t NewOffset = 0;
  707. if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
  708. NewOffset))
  709. continue;
  710. // Get the MI and SUnit for the instruction that defines the original base.
  711. unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
  712. MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
  713. if (!DefMI)
  714. continue;
  715. SUnit *DefSU = getSUnit(DefMI);
  716. if (!DefSU)
  717. continue;
  718. // Get the MI and SUnit for the instruction that defins the new base.
  719. MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
  720. if (!LastMI)
  721. continue;
  722. SUnit *LastSU = getSUnit(LastMI);
  723. if (!LastSU)
  724. continue;
  725. if (Topo.IsReachable(&I, LastSU))
  726. continue;
  727. // Remove the dependence. The value now depends on a prior iteration.
  728. SmallVector<SDep, 4> Deps;
  729. for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
  730. ++P)
  731. if (P->getSUnit() == DefSU)
  732. Deps.push_back(*P);
  733. for (int i = 0, e = Deps.size(); i != e; i++) {
  734. Topo.RemovePred(&I, Deps[i].getSUnit());
  735. I.removePred(Deps[i]);
  736. }
  737. // Remove the chain dependence between the instructions.
  738. Deps.clear();
  739. for (auto &P : LastSU->Preds)
  740. if (P.getSUnit() == &I && P.getKind() == SDep::Order)
  741. Deps.push_back(P);
  742. for (int i = 0, e = Deps.size(); i != e; i++) {
  743. Topo.RemovePred(LastSU, Deps[i].getSUnit());
  744. LastSU->removePred(Deps[i]);
  745. }
  746. // Add a dependence between the new instruction and the instruction
  747. // that defines the new base.
  748. SDep Dep(&I, SDep::Anti, NewBase);
  749. Topo.AddPred(LastSU, &I);
  750. LastSU->addPred(Dep);
  751. // Remember the base and offset information so that we can update the
  752. // instruction during code generation.
  753. InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
  754. }
  755. }
  756. namespace {
  757. // FuncUnitSorter - Comparison operator used to sort instructions by
  758. // the number of functional unit choices.
  759. struct FuncUnitSorter {
  760. const InstrItineraryData *InstrItins;
  761. const MCSubtargetInfo *STI;
  762. DenseMap<unsigned, unsigned> Resources;
  763. FuncUnitSorter(const TargetSubtargetInfo &TSI)
  764. : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
  765. // Compute the number of functional unit alternatives needed
  766. // at each stage, and take the minimum value. We prioritize the
  767. // instructions by the least number of choices first.
  768. unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
  769. unsigned SchedClass = Inst->getDesc().getSchedClass();
  770. unsigned min = UINT_MAX;
  771. if (InstrItins && !InstrItins->isEmpty()) {
  772. for (const InstrStage &IS :
  773. make_range(InstrItins->beginStage(SchedClass),
  774. InstrItins->endStage(SchedClass))) {
  775. unsigned funcUnits = IS.getUnits();
  776. unsigned numAlternatives = countPopulation(funcUnits);
  777. if (numAlternatives < min) {
  778. min = numAlternatives;
  779. F = funcUnits;
  780. }
  781. }
  782. return min;
  783. }
  784. if (STI && STI->getSchedModel().hasInstrSchedModel()) {
  785. const MCSchedClassDesc *SCDesc =
  786. STI->getSchedModel().getSchedClassDesc(SchedClass);
  787. if (!SCDesc->isValid())
  788. // No valid Schedule Class Desc for schedClass, should be
  789. // Pseudo/PostRAPseudo
  790. return min;
  791. for (const MCWriteProcResEntry &PRE :
  792. make_range(STI->getWriteProcResBegin(SCDesc),
  793. STI->getWriteProcResEnd(SCDesc))) {
  794. if (!PRE.Cycles)
  795. continue;
  796. const MCProcResourceDesc *ProcResource =
  797. STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
  798. unsigned NumUnits = ProcResource->NumUnits;
  799. if (NumUnits < min) {
  800. min = NumUnits;
  801. F = PRE.ProcResourceIdx;
  802. }
  803. }
  804. return min;
  805. }
  806. llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
  807. }
  808. // Compute the critical resources needed by the instruction. This
  809. // function records the functional units needed by instructions that
  810. // must use only one functional unit. We use this as a tie breaker
  811. // for computing the resource MII. The instrutions that require
  812. // the same, highly used, functional unit have high priority.
  813. void calcCriticalResources(MachineInstr &MI) {
  814. unsigned SchedClass = MI.getDesc().getSchedClass();
  815. if (InstrItins && !InstrItins->isEmpty()) {
  816. for (const InstrStage &IS :
  817. make_range(InstrItins->beginStage(SchedClass),
  818. InstrItins->endStage(SchedClass))) {
  819. unsigned FuncUnits = IS.getUnits();
  820. if (countPopulation(FuncUnits) == 1)
  821. Resources[FuncUnits]++;
  822. }
  823. return;
  824. }
  825. if (STI && STI->getSchedModel().hasInstrSchedModel()) {
  826. const MCSchedClassDesc *SCDesc =
  827. STI->getSchedModel().getSchedClassDesc(SchedClass);
  828. if (!SCDesc->isValid())
  829. // No valid Schedule Class Desc for schedClass, should be
  830. // Pseudo/PostRAPseudo
  831. return;
  832. for (const MCWriteProcResEntry &PRE :
  833. make_range(STI->getWriteProcResBegin(SCDesc),
  834. STI->getWriteProcResEnd(SCDesc))) {
  835. if (!PRE.Cycles)
  836. continue;
  837. Resources[PRE.ProcResourceIdx]++;
  838. }
  839. return;
  840. }
  841. llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
  842. }
  843. /// Return true if IS1 has less priority than IS2.
  844. bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
  845. unsigned F1 = 0, F2 = 0;
  846. unsigned MFUs1 = minFuncUnits(IS1, F1);
  847. unsigned MFUs2 = minFuncUnits(IS2, F2);
  848. if (MFUs1 == 1 && MFUs2 == 1)
  849. return Resources.lookup(F1) < Resources.lookup(F2);
  850. return MFUs1 > MFUs2;
  851. }
  852. };
  853. } // end anonymous namespace
  854. /// Calculate the resource constrained minimum initiation interval for the
  855. /// specified loop. We use the DFA to model the resources needed for
  856. /// each instruction, and we ignore dependences. A different DFA is created
  857. /// for each cycle that is required. When adding a new instruction, we attempt
  858. /// to add it to each existing DFA, until a legal space is found. If the
  859. /// instruction cannot be reserved in an existing DFA, we create a new one.
  860. unsigned SwingSchedulerDAG::calculateResMII() {
  861. LLVM_DEBUG(dbgs() << "calculateResMII:\n");
  862. SmallVector<ResourceManager*, 8> Resources;
  863. MachineBasicBlock *MBB = Loop.getHeader();
  864. Resources.push_back(new ResourceManager(&MF.getSubtarget()));
  865. // Sort the instructions by the number of available choices for scheduling,
  866. // least to most. Use the number of critical resources as the tie breaker.
  867. FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
  868. for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
  869. E = MBB->getFirstTerminator();
  870. I != E; ++I)
  871. FUS.calcCriticalResources(*I);
  872. PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
  873. FuncUnitOrder(FUS);
  874. for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
  875. E = MBB->getFirstTerminator();
  876. I != E; ++I)
  877. FuncUnitOrder.push(&*I);
  878. while (!FuncUnitOrder.empty()) {
  879. MachineInstr *MI = FuncUnitOrder.top();
  880. FuncUnitOrder.pop();
  881. if (TII->isZeroCost(MI->getOpcode()))
  882. continue;
  883. // Attempt to reserve the instruction in an existing DFA. At least one
  884. // DFA is needed for each cycle.
  885. unsigned NumCycles = getSUnit(MI)->Latency;
  886. unsigned ReservedCycles = 0;
  887. SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
  888. SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
  889. LLVM_DEBUG({
  890. dbgs() << "Trying to reserve resource for " << NumCycles
  891. << " cycles for \n";
  892. MI->dump();
  893. });
  894. for (unsigned C = 0; C < NumCycles; ++C)
  895. while (RI != RE) {
  896. if ((*RI++)->canReserveResources(*MI)) {
  897. ++ReservedCycles;
  898. break;
  899. }
  900. }
  901. // Start reserving resources using existing DFAs.
  902. for (unsigned C = 0; C < ReservedCycles; ++C) {
  903. --RI;
  904. (*RI)->reserveResources(*MI);
  905. }
  906. LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
  907. << ", NumCycles:" << NumCycles << "\n");
  908. // Add new DFAs, if needed, to reserve resources.
  909. for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
  910. LLVM_DEBUG(if (SwpDebugResource) dbgs()
  911. << "NewResource created to reserve resources"
  912. << "\n");
  913. ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
  914. assert(NewResource->canReserveResources(*MI) && "Reserve error.");
  915. NewResource->reserveResources(*MI);
  916. Resources.push_back(NewResource);
  917. }
  918. }
  919. int Resmii = Resources.size();
  920. LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii << "\n");
  921. // Delete the memory for each of the DFAs that were created earlier.
  922. for (ResourceManager *RI : Resources) {
  923. ResourceManager *D = RI;
  924. delete D;
  925. }
  926. Resources.clear();
  927. return Resmii;
  928. }
  929. /// Calculate the recurrence-constrainted minimum initiation interval.
  930. /// Iterate over each circuit. Compute the delay(c) and distance(c)
  931. /// for each circuit. The II needs to satisfy the inequality
  932. /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
  933. /// II that satisfies the inequality, and the RecMII is the maximum
  934. /// of those values.
  935. unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
  936. unsigned RecMII = 0;
  937. for (NodeSet &Nodes : NodeSets) {
  938. if (Nodes.empty())
  939. continue;
  940. unsigned Delay = Nodes.getLatency();
  941. unsigned Distance = 1;
  942. // ii = ceil(delay / distance)
  943. unsigned CurMII = (Delay + Distance - 1) / Distance;
  944. Nodes.setRecMII(CurMII);
  945. if (CurMII > RecMII)
  946. RecMII = CurMII;
  947. }
  948. return RecMII;
  949. }
  950. /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
  951. /// but we do this to find the circuits, and then change them back.
  952. static void swapAntiDependences(std::vector<SUnit> &SUnits) {
  953. SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
  954. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  955. SUnit *SU = &SUnits[i];
  956. for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
  957. IP != EP; ++IP) {
  958. if (IP->getKind() != SDep::Anti)
  959. continue;
  960. DepsAdded.push_back(std::make_pair(SU, *IP));
  961. }
  962. }
  963. for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
  964. E = DepsAdded.end();
  965. I != E; ++I) {
  966. // Remove this anti dependency and add one in the reverse direction.
  967. SUnit *SU = I->first;
  968. SDep &D = I->second;
  969. SUnit *TargetSU = D.getSUnit();
  970. unsigned Reg = D.getReg();
  971. unsigned Lat = D.getLatency();
  972. SU->removePred(D);
  973. SDep Dep(SU, SDep::Anti, Reg);
  974. Dep.setLatency(Lat);
  975. TargetSU->addPred(Dep);
  976. }
  977. }
  978. /// Create the adjacency structure of the nodes in the graph.
  979. void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
  980. SwingSchedulerDAG *DAG) {
  981. BitVector Added(SUnits.size());
  982. DenseMap<int, int> OutputDeps;
  983. for (int i = 0, e = SUnits.size(); i != e; ++i) {
  984. Added.reset();
  985. // Add any successor to the adjacency matrix and exclude duplicates.
  986. for (auto &SI : SUnits[i].Succs) {
  987. // Only create a back-edge on the first and last nodes of a dependence
  988. // chain. This records any chains and adds them later.
  989. if (SI.getKind() == SDep::Output) {
  990. int N = SI.getSUnit()->NodeNum;
  991. int BackEdge = i;
  992. auto Dep = OutputDeps.find(BackEdge);
  993. if (Dep != OutputDeps.end()) {
  994. BackEdge = Dep->second;
  995. OutputDeps.erase(Dep);
  996. }
  997. OutputDeps[N] = BackEdge;
  998. }
  999. // Do not process a boundary node, an artificial node.
  1000. // A back-edge is processed only if it goes to a Phi.
  1001. if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
  1002. (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
  1003. continue;
  1004. int N = SI.getSUnit()->NodeNum;
  1005. if (!Added.test(N)) {
  1006. AdjK[i].push_back(N);
  1007. Added.set(N);
  1008. }
  1009. }
  1010. // A chain edge between a store and a load is treated as a back-edge in the
  1011. // adjacency matrix.
  1012. for (auto &PI : SUnits[i].Preds) {
  1013. if (!SUnits[i].getInstr()->mayStore() ||
  1014. !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
  1015. continue;
  1016. if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
  1017. int N = PI.getSUnit()->NodeNum;
  1018. if (!Added.test(N)) {
  1019. AdjK[i].push_back(N);
  1020. Added.set(N);
  1021. }
  1022. }
  1023. }
  1024. }
  1025. // Add back-edges in the adjacency matrix for the output dependences.
  1026. for (auto &OD : OutputDeps)
  1027. if (!Added.test(OD.second)) {
  1028. AdjK[OD.first].push_back(OD.second);
  1029. Added.set(OD.second);
  1030. }
  1031. }
  1032. /// Identify an elementary circuit in the dependence graph starting at the
  1033. /// specified node.
  1034. bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
  1035. bool HasBackedge) {
  1036. SUnit *SV = &SUnits[V];
  1037. bool F = false;
  1038. Stack.insert(SV);
  1039. Blocked.set(V);
  1040. for (auto W : AdjK[V]) {
  1041. if (NumPaths > MaxPaths)
  1042. break;
  1043. if (W < S)
  1044. continue;
  1045. if (W == S) {
  1046. if (!HasBackedge)
  1047. NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
  1048. F = true;
  1049. ++NumPaths;
  1050. break;
  1051. } else if (!Blocked.test(W)) {
  1052. if (circuit(W, S, NodeSets,
  1053. Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
  1054. F = true;
  1055. }
  1056. }
  1057. if (F)
  1058. unblock(V);
  1059. else {
  1060. for (auto W : AdjK[V]) {
  1061. if (W < S)
  1062. continue;
  1063. if (B[W].count(SV) == 0)
  1064. B[W].insert(SV);
  1065. }
  1066. }
  1067. Stack.pop_back();
  1068. return F;
  1069. }
  1070. /// Unblock a node in the circuit finding algorithm.
  1071. void SwingSchedulerDAG::Circuits::unblock(int U) {
  1072. Blocked.reset(U);
  1073. SmallPtrSet<SUnit *, 4> &BU = B[U];
  1074. while (!BU.empty()) {
  1075. SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
  1076. assert(SI != BU.end() && "Invalid B set.");
  1077. SUnit *W = *SI;
  1078. BU.erase(W);
  1079. if (Blocked.test(W->NodeNum))
  1080. unblock(W->NodeNum);
  1081. }
  1082. }
  1083. /// Identify all the elementary circuits in the dependence graph using
  1084. /// Johnson's circuit algorithm.
  1085. void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
  1086. // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
  1087. // but we do this to find the circuits, and then change them back.
  1088. swapAntiDependences(SUnits);
  1089. Circuits Cir(SUnits, Topo);
  1090. // Create the adjacency structure.
  1091. Cir.createAdjacencyStructure(this);
  1092. for (int i = 0, e = SUnits.size(); i != e; ++i) {
  1093. Cir.reset();
  1094. Cir.circuit(i, i, NodeSets);
  1095. }
  1096. // Change the dependences back so that we've created a DAG again.
  1097. swapAntiDependences(SUnits);
  1098. }
  1099. // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
  1100. // is loop-carried to the USE in next iteration. This will help pipeliner avoid
  1101. // additional copies that are needed across iterations. An artificial dependence
  1102. // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
  1103. // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
  1104. // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
  1105. // PHI-------True-Dep------> USEOfPhi
  1106. // The mutation creates
  1107. // USEOfPHI -------Artificial-Dep---> SRCOfCopy
  1108. // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
  1109. // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
  1110. // late to avoid additional copies across iterations. The possible scheduling
  1111. // order would be
  1112. // USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
  1113. void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
  1114. for (SUnit &SU : DAG->SUnits) {
  1115. // Find the COPY/REG_SEQUENCE instruction.
  1116. if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
  1117. continue;
  1118. // Record the loop carried PHIs.
  1119. SmallVector<SUnit *, 4> PHISUs;
  1120. // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
  1121. SmallVector<SUnit *, 4> SrcSUs;
  1122. for (auto &Dep : SU.Preds) {
  1123. SUnit *TmpSU = Dep.getSUnit();
  1124. MachineInstr *TmpMI = TmpSU->getInstr();
  1125. SDep::Kind DepKind = Dep.getKind();
  1126. // Save the loop carried PHI.
  1127. if (DepKind == SDep::Anti && TmpMI->isPHI())
  1128. PHISUs.push_back(TmpSU);
  1129. // Save the source of COPY/REG_SEQUENCE.
  1130. // If the source has no pre-decessors, we will end up creating cycles.
  1131. else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
  1132. SrcSUs.push_back(TmpSU);
  1133. }
  1134. if (PHISUs.size() == 0 || SrcSUs.size() == 0)
  1135. continue;
  1136. // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
  1137. // SUnit to the container.
  1138. SmallVector<SUnit *, 8> UseSUs;
  1139. for (auto I = PHISUs.begin(); I != PHISUs.end(); ++I) {
  1140. for (auto &Dep : (*I)->Succs) {
  1141. if (Dep.getKind() != SDep::Data)
  1142. continue;
  1143. SUnit *TmpSU = Dep.getSUnit();
  1144. MachineInstr *TmpMI = TmpSU->getInstr();
  1145. if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
  1146. PHISUs.push_back(TmpSU);
  1147. continue;
  1148. }
  1149. UseSUs.push_back(TmpSU);
  1150. }
  1151. }
  1152. if (UseSUs.size() == 0)
  1153. continue;
  1154. SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
  1155. // Add the artificial dependencies if it does not form a cycle.
  1156. for (auto I : UseSUs) {
  1157. for (auto Src : SrcSUs) {
  1158. if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
  1159. Src->addPred(SDep(I, SDep::Artificial));
  1160. SDAG->Topo.AddPred(Src, I);
  1161. }
  1162. }
  1163. }
  1164. }
  1165. }
  1166. /// Return true for DAG nodes that we ignore when computing the cost functions.
  1167. /// We ignore the back-edge recurrence in order to avoid unbounded recursion
  1168. /// in the calculation of the ASAP, ALAP, etc functions.
  1169. static bool ignoreDependence(const SDep &D, bool isPred) {
  1170. if (D.isArtificial())
  1171. return true;
  1172. return D.getKind() == SDep::Anti && isPred;
  1173. }
  1174. /// Compute several functions need to order the nodes for scheduling.
  1175. /// ASAP - Earliest time to schedule a node.
  1176. /// ALAP - Latest time to schedule a node.
  1177. /// MOV - Mobility function, difference between ALAP and ASAP.
  1178. /// D - Depth of each node.
  1179. /// H - Height of each node.
  1180. void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
  1181. ScheduleInfo.resize(SUnits.size());
  1182. LLVM_DEBUG({
  1183. for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
  1184. E = Topo.end();
  1185. I != E; ++I) {
  1186. const SUnit &SU = SUnits[*I];
  1187. dumpNode(SU);
  1188. }
  1189. });
  1190. int maxASAP = 0;
  1191. // Compute ASAP and ZeroLatencyDepth.
  1192. for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
  1193. E = Topo.end();
  1194. I != E; ++I) {
  1195. int asap = 0;
  1196. int zeroLatencyDepth = 0;
  1197. SUnit *SU = &SUnits[*I];
  1198. for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
  1199. EP = SU->Preds.end();
  1200. IP != EP; ++IP) {
  1201. SUnit *pred = IP->getSUnit();
  1202. if (IP->getLatency() == 0)
  1203. zeroLatencyDepth =
  1204. std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
  1205. if (ignoreDependence(*IP, true))
  1206. continue;
  1207. asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
  1208. getDistance(pred, SU, *IP) * MII));
  1209. }
  1210. maxASAP = std::max(maxASAP, asap);
  1211. ScheduleInfo[*I].ASAP = asap;
  1212. ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
  1213. }
  1214. // Compute ALAP, ZeroLatencyHeight, and MOV.
  1215. for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
  1216. E = Topo.rend();
  1217. I != E; ++I) {
  1218. int alap = maxASAP;
  1219. int zeroLatencyHeight = 0;
  1220. SUnit *SU = &SUnits[*I];
  1221. for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
  1222. ES = SU->Succs.end();
  1223. IS != ES; ++IS) {
  1224. SUnit *succ = IS->getSUnit();
  1225. if (IS->getLatency() == 0)
  1226. zeroLatencyHeight =
  1227. std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
  1228. if (ignoreDependence(*IS, true))
  1229. continue;
  1230. alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
  1231. getDistance(SU, succ, *IS) * MII));
  1232. }
  1233. ScheduleInfo[*I].ALAP = alap;
  1234. ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
  1235. }
  1236. // After computing the node functions, compute the summary for each node set.
  1237. for (NodeSet &I : NodeSets)
  1238. I.computeNodeSetInfo(this);
  1239. LLVM_DEBUG({
  1240. for (unsigned i = 0; i < SUnits.size(); i++) {
  1241. dbgs() << "\tNode " << i << ":\n";
  1242. dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
  1243. dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
  1244. dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
  1245. dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
  1246. dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
  1247. dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
  1248. dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
  1249. }
  1250. });
  1251. }
  1252. /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
  1253. /// as the predecessors of the elements of NodeOrder that are not also in
  1254. /// NodeOrder.
  1255. static bool pred_L(SetVector<SUnit *> &NodeOrder,
  1256. SmallSetVector<SUnit *, 8> &Preds,
  1257. const NodeSet *S = nullptr) {
  1258. Preds.clear();
  1259. for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
  1260. I != E; ++I) {
  1261. for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
  1262. PI != PE; ++PI) {
  1263. if (S && S->count(PI->getSUnit()) == 0)
  1264. continue;
  1265. if (ignoreDependence(*PI, true))
  1266. continue;
  1267. if (NodeOrder.count(PI->getSUnit()) == 0)
  1268. Preds.insert(PI->getSUnit());
  1269. }
  1270. // Back-edges are predecessors with an anti-dependence.
  1271. for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
  1272. ES = (*I)->Succs.end();
  1273. IS != ES; ++IS) {
  1274. if (IS->getKind() != SDep::Anti)
  1275. continue;
  1276. if (S && S->count(IS->getSUnit()) == 0)
  1277. continue;
  1278. if (NodeOrder.count(IS->getSUnit()) == 0)
  1279. Preds.insert(IS->getSUnit());
  1280. }
  1281. }
  1282. return !Preds.empty();
  1283. }
  1284. /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
  1285. /// as the successors of the elements of NodeOrder that are not also in
  1286. /// NodeOrder.
  1287. static bool succ_L(SetVector<SUnit *> &NodeOrder,
  1288. SmallSetVector<SUnit *, 8> &Succs,
  1289. const NodeSet *S = nullptr) {
  1290. Succs.clear();
  1291. for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
  1292. I != E; ++I) {
  1293. for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
  1294. SI != SE; ++SI) {
  1295. if (S && S->count(SI->getSUnit()) == 0)
  1296. continue;
  1297. if (ignoreDependence(*SI, false))
  1298. continue;
  1299. if (NodeOrder.count(SI->getSUnit()) == 0)
  1300. Succs.insert(SI->getSUnit());
  1301. }
  1302. for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
  1303. PE = (*I)->Preds.end();
  1304. PI != PE; ++PI) {
  1305. if (PI->getKind() != SDep::Anti)
  1306. continue;
  1307. if (S && S->count(PI->getSUnit()) == 0)
  1308. continue;
  1309. if (NodeOrder.count(PI->getSUnit()) == 0)
  1310. Succs.insert(PI->getSUnit());
  1311. }
  1312. }
  1313. return !Succs.empty();
  1314. }
  1315. /// Return true if there is a path from the specified node to any of the nodes
  1316. /// in DestNodes. Keep track and return the nodes in any path.
  1317. static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
  1318. SetVector<SUnit *> &DestNodes,
  1319. SetVector<SUnit *> &Exclude,
  1320. SmallPtrSet<SUnit *, 8> &Visited) {
  1321. if (Cur->isBoundaryNode())
  1322. return false;
  1323. if (Exclude.count(Cur) != 0)
  1324. return false;
  1325. if (DestNodes.count(Cur) != 0)
  1326. return true;
  1327. if (!Visited.insert(Cur).second)
  1328. return Path.count(Cur) != 0;
  1329. bool FoundPath = false;
  1330. for (auto &SI : Cur->Succs)
  1331. FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
  1332. for (auto &PI : Cur->Preds)
  1333. if (PI.getKind() == SDep::Anti)
  1334. FoundPath |=
  1335. computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
  1336. if (FoundPath)
  1337. Path.insert(Cur);
  1338. return FoundPath;
  1339. }
  1340. /// Return true if Set1 is a subset of Set2.
  1341. template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
  1342. for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
  1343. if (Set2.count(*I) == 0)
  1344. return false;
  1345. return true;
  1346. }
  1347. /// Compute the live-out registers for the instructions in a node-set.
  1348. /// The live-out registers are those that are defined in the node-set,
  1349. /// but not used. Except for use operands of Phis.
  1350. static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
  1351. NodeSet &NS) {
  1352. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1353. MachineRegisterInfo &MRI = MF.getRegInfo();
  1354. SmallVector<RegisterMaskPair, 8> LiveOutRegs;
  1355. SmallSet<unsigned, 4> Uses;
  1356. for (SUnit *SU : NS) {
  1357. const MachineInstr *MI = SU->getInstr();
  1358. if (MI->isPHI())
  1359. continue;
  1360. for (const MachineOperand &MO : MI->operands())
  1361. if (MO.isReg() && MO.isUse()) {
  1362. unsigned Reg = MO.getReg();
  1363. if (TargetRegisterInfo::isVirtualRegister(Reg))
  1364. Uses.insert(Reg);
  1365. else if (MRI.isAllocatable(Reg))
  1366. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  1367. Uses.insert(*Units);
  1368. }
  1369. }
  1370. for (SUnit *SU : NS)
  1371. for (const MachineOperand &MO : SU->getInstr()->operands())
  1372. if (MO.isReg() && MO.isDef() && !MO.isDead()) {
  1373. unsigned Reg = MO.getReg();
  1374. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  1375. if (!Uses.count(Reg))
  1376. LiveOutRegs.push_back(RegisterMaskPair(Reg,
  1377. LaneBitmask::getNone()));
  1378. } else if (MRI.isAllocatable(Reg)) {
  1379. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  1380. if (!Uses.count(*Units))
  1381. LiveOutRegs.push_back(RegisterMaskPair(*Units,
  1382. LaneBitmask::getNone()));
  1383. }
  1384. }
  1385. RPTracker.addLiveRegs(LiveOutRegs);
  1386. }
  1387. /// A heuristic to filter nodes in recurrent node-sets if the register
  1388. /// pressure of a set is too high.
  1389. void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
  1390. for (auto &NS : NodeSets) {
  1391. // Skip small node-sets since they won't cause register pressure problems.
  1392. if (NS.size() <= 2)
  1393. continue;
  1394. IntervalPressure RecRegPressure;
  1395. RegPressureTracker RecRPTracker(RecRegPressure);
  1396. RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
  1397. computeLiveOuts(MF, RecRPTracker, NS);
  1398. RecRPTracker.closeBottom();
  1399. std::vector<SUnit *> SUnits(NS.begin(), NS.end());
  1400. llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
  1401. return A->NodeNum > B->NodeNum;
  1402. });
  1403. for (auto &SU : SUnits) {
  1404. // Since we're computing the register pressure for a subset of the
  1405. // instructions in a block, we need to set the tracker for each
  1406. // instruction in the node-set. The tracker is set to the instruction
  1407. // just after the one we're interested in.
  1408. MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
  1409. RecRPTracker.setPos(std::next(CurInstI));
  1410. RegPressureDelta RPDelta;
  1411. ArrayRef<PressureChange> CriticalPSets;
  1412. RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
  1413. CriticalPSets,
  1414. RecRegPressure.MaxSetPressure);
  1415. if (RPDelta.Excess.isValid()) {
  1416. LLVM_DEBUG(
  1417. dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
  1418. << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
  1419. << ":" << RPDelta.Excess.getUnitInc());
  1420. NS.setExceedPressure(SU);
  1421. break;
  1422. }
  1423. RecRPTracker.recede();
  1424. }
  1425. }
  1426. }
  1427. /// A heuristic to colocate node sets that have the same set of
  1428. /// successors.
  1429. void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
  1430. unsigned Colocate = 0;
  1431. for (int i = 0, e = NodeSets.size(); i < e; ++i) {
  1432. NodeSet &N1 = NodeSets[i];
  1433. SmallSetVector<SUnit *, 8> S1;
  1434. if (N1.empty() || !succ_L(N1, S1))
  1435. continue;
  1436. for (int j = i + 1; j < e; ++j) {
  1437. NodeSet &N2 = NodeSets[j];
  1438. if (N1.compareRecMII(N2) != 0)
  1439. continue;
  1440. SmallSetVector<SUnit *, 8> S2;
  1441. if (N2.empty() || !succ_L(N2, S2))
  1442. continue;
  1443. if (isSubset(S1, S2) && S1.size() == S2.size()) {
  1444. N1.setColocate(++Colocate);
  1445. N2.setColocate(Colocate);
  1446. break;
  1447. }
  1448. }
  1449. }
  1450. }
  1451. /// Check if the existing node-sets are profitable. If not, then ignore the
  1452. /// recurrent node-sets, and attempt to schedule all nodes together. This is
  1453. /// a heuristic. If the MII is large and all the recurrent node-sets are small,
  1454. /// then it's best to try to schedule all instructions together instead of
  1455. /// starting with the recurrent node-sets.
  1456. void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
  1457. // Look for loops with a large MII.
  1458. if (MII < 17)
  1459. return;
  1460. // Check if the node-set contains only a simple add recurrence.
  1461. for (auto &NS : NodeSets) {
  1462. if (NS.getRecMII() > 2)
  1463. return;
  1464. if (NS.getMaxDepth() > MII)
  1465. return;
  1466. }
  1467. NodeSets.clear();
  1468. LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
  1469. return;
  1470. }
  1471. /// Add the nodes that do not belong to a recurrence set into groups
  1472. /// based upon connected componenets.
  1473. void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
  1474. SetVector<SUnit *> NodesAdded;
  1475. SmallPtrSet<SUnit *, 8> Visited;
  1476. // Add the nodes that are on a path between the previous node sets and
  1477. // the current node set.
  1478. for (NodeSet &I : NodeSets) {
  1479. SmallSetVector<SUnit *, 8> N;
  1480. // Add the nodes from the current node set to the previous node set.
  1481. if (succ_L(I, N)) {
  1482. SetVector<SUnit *> Path;
  1483. for (SUnit *NI : N) {
  1484. Visited.clear();
  1485. computePath(NI, Path, NodesAdded, I, Visited);
  1486. }
  1487. if (!Path.empty())
  1488. I.insert(Path.begin(), Path.end());
  1489. }
  1490. // Add the nodes from the previous node set to the current node set.
  1491. N.clear();
  1492. if (succ_L(NodesAdded, N)) {
  1493. SetVector<SUnit *> Path;
  1494. for (SUnit *NI : N) {
  1495. Visited.clear();
  1496. computePath(NI, Path, I, NodesAdded, Visited);
  1497. }
  1498. if (!Path.empty())
  1499. I.insert(Path.begin(), Path.end());
  1500. }
  1501. NodesAdded.insert(I.begin(), I.end());
  1502. }
  1503. // Create a new node set with the connected nodes of any successor of a node
  1504. // in a recurrent set.
  1505. NodeSet NewSet;
  1506. SmallSetVector<SUnit *, 8> N;
  1507. if (succ_L(NodesAdded, N))
  1508. for (SUnit *I : N)
  1509. addConnectedNodes(I, NewSet, NodesAdded);
  1510. if (!NewSet.empty())
  1511. NodeSets.push_back(NewSet);
  1512. // Create a new node set with the connected nodes of any predecessor of a node
  1513. // in a recurrent set.
  1514. NewSet.clear();
  1515. if (pred_L(NodesAdded, N))
  1516. for (SUnit *I : N)
  1517. addConnectedNodes(I, NewSet, NodesAdded);
  1518. if (!NewSet.empty())
  1519. NodeSets.push_back(NewSet);
  1520. // Create new nodes sets with the connected nodes any remaining node that
  1521. // has no predecessor.
  1522. for (unsigned i = 0; i < SUnits.size(); ++i) {
  1523. SUnit *SU = &SUnits[i];
  1524. if (NodesAdded.count(SU) == 0) {
  1525. NewSet.clear();
  1526. addConnectedNodes(SU, NewSet, NodesAdded);
  1527. if (!NewSet.empty())
  1528. NodeSets.push_back(NewSet);
  1529. }
  1530. }
  1531. }
  1532. /// Add the node to the set, and add all of its connected nodes to the set.
  1533. void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
  1534. SetVector<SUnit *> &NodesAdded) {
  1535. NewSet.insert(SU);
  1536. NodesAdded.insert(SU);
  1537. for (auto &SI : SU->Succs) {
  1538. SUnit *Successor = SI.getSUnit();
  1539. if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
  1540. addConnectedNodes(Successor, NewSet, NodesAdded);
  1541. }
  1542. for (auto &PI : SU->Preds) {
  1543. SUnit *Predecessor = PI.getSUnit();
  1544. if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
  1545. addConnectedNodes(Predecessor, NewSet, NodesAdded);
  1546. }
  1547. }
  1548. /// Return true if Set1 contains elements in Set2. The elements in common
  1549. /// are returned in a different container.
  1550. static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
  1551. SmallSetVector<SUnit *, 8> &Result) {
  1552. Result.clear();
  1553. for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
  1554. SUnit *SU = Set1[i];
  1555. if (Set2.count(SU) != 0)
  1556. Result.insert(SU);
  1557. }
  1558. return !Result.empty();
  1559. }
  1560. /// Merge the recurrence node sets that have the same initial node.
  1561. void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
  1562. for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
  1563. ++I) {
  1564. NodeSet &NI = *I;
  1565. for (NodeSetType::iterator J = I + 1; J != E;) {
  1566. NodeSet &NJ = *J;
  1567. if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
  1568. if (NJ.compareRecMII(NI) > 0)
  1569. NI.setRecMII(NJ.getRecMII());
  1570. for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
  1571. ++NII)
  1572. I->insert(*NII);
  1573. NodeSets.erase(J);
  1574. E = NodeSets.end();
  1575. } else {
  1576. ++J;
  1577. }
  1578. }
  1579. }
  1580. }
  1581. /// Remove nodes that have been scheduled in previous NodeSets.
  1582. void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
  1583. for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
  1584. ++I)
  1585. for (NodeSetType::iterator J = I + 1; J != E;) {
  1586. J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
  1587. if (J->empty()) {
  1588. NodeSets.erase(J);
  1589. E = NodeSets.end();
  1590. } else {
  1591. ++J;
  1592. }
  1593. }
  1594. }
  1595. /// Compute an ordered list of the dependence graph nodes, which
  1596. /// indicates the order that the nodes will be scheduled. This is a
  1597. /// two-level algorithm. First, a partial order is created, which
  1598. /// consists of a list of sets ordered from highest to lowest priority.
  1599. void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
  1600. SmallSetVector<SUnit *, 8> R;
  1601. NodeOrder.clear();
  1602. for (auto &Nodes : NodeSets) {
  1603. LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
  1604. OrderKind Order;
  1605. SmallSetVector<SUnit *, 8> N;
  1606. if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
  1607. R.insert(N.begin(), N.end());
  1608. Order = BottomUp;
  1609. LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
  1610. } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
  1611. R.insert(N.begin(), N.end());
  1612. Order = TopDown;
  1613. LLVM_DEBUG(dbgs() << " Top down (succs) ");
  1614. } else if (isIntersect(N, Nodes, R)) {
  1615. // If some of the successors are in the existing node-set, then use the
  1616. // top-down ordering.
  1617. Order = TopDown;
  1618. LLVM_DEBUG(dbgs() << " Top down (intersect) ");
  1619. } else if (NodeSets.size() == 1) {
  1620. for (auto &N : Nodes)
  1621. if (N->Succs.size() == 0)
  1622. R.insert(N);
  1623. Order = BottomUp;
  1624. LLVM_DEBUG(dbgs() << " Bottom up (all) ");
  1625. } else {
  1626. // Find the node with the highest ASAP.
  1627. SUnit *maxASAP = nullptr;
  1628. for (SUnit *SU : Nodes) {
  1629. if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
  1630. (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
  1631. maxASAP = SU;
  1632. }
  1633. R.insert(maxASAP);
  1634. Order = BottomUp;
  1635. LLVM_DEBUG(dbgs() << " Bottom up (default) ");
  1636. }
  1637. while (!R.empty()) {
  1638. if (Order == TopDown) {
  1639. // Choose the node with the maximum height. If more than one, choose
  1640. // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
  1641. // choose the node with the lowest MOV.
  1642. while (!R.empty()) {
  1643. SUnit *maxHeight = nullptr;
  1644. for (SUnit *I : R) {
  1645. if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
  1646. maxHeight = I;
  1647. else if (getHeight(I) == getHeight(maxHeight) &&
  1648. getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
  1649. maxHeight = I;
  1650. else if (getHeight(I) == getHeight(maxHeight) &&
  1651. getZeroLatencyHeight(I) ==
  1652. getZeroLatencyHeight(maxHeight) &&
  1653. getMOV(I) < getMOV(maxHeight))
  1654. maxHeight = I;
  1655. }
  1656. NodeOrder.insert(maxHeight);
  1657. LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
  1658. R.remove(maxHeight);
  1659. for (const auto &I : maxHeight->Succs) {
  1660. if (Nodes.count(I.getSUnit()) == 0)
  1661. continue;
  1662. if (NodeOrder.count(I.getSUnit()) != 0)
  1663. continue;
  1664. if (ignoreDependence(I, false))
  1665. continue;
  1666. R.insert(I.getSUnit());
  1667. }
  1668. // Back-edges are predecessors with an anti-dependence.
  1669. for (const auto &I : maxHeight->Preds) {
  1670. if (I.getKind() != SDep::Anti)
  1671. continue;
  1672. if (Nodes.count(I.getSUnit()) == 0)
  1673. continue;
  1674. if (NodeOrder.count(I.getSUnit()) != 0)
  1675. continue;
  1676. R.insert(I.getSUnit());
  1677. }
  1678. }
  1679. Order = BottomUp;
  1680. LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
  1681. SmallSetVector<SUnit *, 8> N;
  1682. if (pred_L(NodeOrder, N, &Nodes))
  1683. R.insert(N.begin(), N.end());
  1684. } else {
  1685. // Choose the node with the maximum depth. If more than one, choose
  1686. // the node with the maximum ZeroLatencyDepth. If still more than one,
  1687. // choose the node with the lowest MOV.
  1688. while (!R.empty()) {
  1689. SUnit *maxDepth = nullptr;
  1690. for (SUnit *I : R) {
  1691. if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
  1692. maxDepth = I;
  1693. else if (getDepth(I) == getDepth(maxDepth) &&
  1694. getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
  1695. maxDepth = I;
  1696. else if (getDepth(I) == getDepth(maxDepth) &&
  1697. getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
  1698. getMOV(I) < getMOV(maxDepth))
  1699. maxDepth = I;
  1700. }
  1701. NodeOrder.insert(maxDepth);
  1702. LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
  1703. R.remove(maxDepth);
  1704. if (Nodes.isExceedSU(maxDepth)) {
  1705. Order = TopDown;
  1706. R.clear();
  1707. R.insert(Nodes.getNode(0));
  1708. break;
  1709. }
  1710. for (const auto &I : maxDepth->Preds) {
  1711. if (Nodes.count(I.getSUnit()) == 0)
  1712. continue;
  1713. if (NodeOrder.count(I.getSUnit()) != 0)
  1714. continue;
  1715. R.insert(I.getSUnit());
  1716. }
  1717. // Back-edges are predecessors with an anti-dependence.
  1718. for (const auto &I : maxDepth->Succs) {
  1719. if (I.getKind() != SDep::Anti)
  1720. continue;
  1721. if (Nodes.count(I.getSUnit()) == 0)
  1722. continue;
  1723. if (NodeOrder.count(I.getSUnit()) != 0)
  1724. continue;
  1725. R.insert(I.getSUnit());
  1726. }
  1727. }
  1728. Order = TopDown;
  1729. LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
  1730. SmallSetVector<SUnit *, 8> N;
  1731. if (succ_L(NodeOrder, N, &Nodes))
  1732. R.insert(N.begin(), N.end());
  1733. }
  1734. }
  1735. LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
  1736. }
  1737. LLVM_DEBUG({
  1738. dbgs() << "Node order: ";
  1739. for (SUnit *I : NodeOrder)
  1740. dbgs() << " " << I->NodeNum << " ";
  1741. dbgs() << "\n";
  1742. });
  1743. }
  1744. /// Process the nodes in the computed order and create the pipelined schedule
  1745. /// of the instructions, if possible. Return true if a schedule is found.
  1746. bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
  1747. if (NodeOrder.empty()){
  1748. LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
  1749. return false;
  1750. }
  1751. bool scheduleFound = false;
  1752. unsigned II = 0;
  1753. // Keep increasing II until a valid schedule is found.
  1754. for (II = MII; II <= MAX_II && !scheduleFound; ++II) {
  1755. Schedule.reset();
  1756. Schedule.setInitiationInterval(II);
  1757. LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
  1758. SetVector<SUnit *>::iterator NI = NodeOrder.begin();
  1759. SetVector<SUnit *>::iterator NE = NodeOrder.end();
  1760. do {
  1761. SUnit *SU = *NI;
  1762. // Compute the schedule time for the instruction, which is based
  1763. // upon the scheduled time for any predecessors/successors.
  1764. int EarlyStart = INT_MIN;
  1765. int LateStart = INT_MAX;
  1766. // These values are set when the size of the schedule window is limited
  1767. // due to chain dependences.
  1768. int SchedEnd = INT_MAX;
  1769. int SchedStart = INT_MIN;
  1770. Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
  1771. II, this);
  1772. LLVM_DEBUG({
  1773. dbgs() << "\n";
  1774. dbgs() << "Inst (" << SU->NodeNum << ") ";
  1775. SU->getInstr()->dump();
  1776. dbgs() << "\n";
  1777. });
  1778. LLVM_DEBUG({
  1779. dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
  1780. LateStart, SchedEnd, SchedStart);
  1781. });
  1782. if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
  1783. SchedStart > LateStart)
  1784. scheduleFound = false;
  1785. else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
  1786. SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
  1787. scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
  1788. } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
  1789. SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
  1790. scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
  1791. } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
  1792. SchedEnd =
  1793. std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
  1794. // When scheduling a Phi it is better to start at the late cycle and go
  1795. // backwards. The default order may insert the Phi too far away from
  1796. // its first dependence.
  1797. if (SU->getInstr()->isPHI())
  1798. scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
  1799. else
  1800. scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
  1801. } else {
  1802. int FirstCycle = Schedule.getFirstCycle();
  1803. scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
  1804. FirstCycle + getASAP(SU) + II - 1, II);
  1805. }
  1806. // Even if we find a schedule, make sure the schedule doesn't exceed the
  1807. // allowable number of stages. We keep trying if this happens.
  1808. if (scheduleFound)
  1809. if (SwpMaxStages > -1 &&
  1810. Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
  1811. scheduleFound = false;
  1812. LLVM_DEBUG({
  1813. if (!scheduleFound)
  1814. dbgs() << "\tCan't schedule\n";
  1815. });
  1816. } while (++NI != NE && scheduleFound);
  1817. // If a schedule is found, check if it is a valid schedule too.
  1818. if (scheduleFound)
  1819. scheduleFound = Schedule.isValidSchedule(this);
  1820. }
  1821. LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << " (II=" << II
  1822. << ")\n");
  1823. if (scheduleFound)
  1824. Schedule.finalizeSchedule(this);
  1825. else
  1826. Schedule.reset();
  1827. return scheduleFound && Schedule.getMaxStageCount() > 0;
  1828. }
  1829. /// Given a schedule for the loop, generate a new version of the loop,
  1830. /// and replace the old version. This function generates a prolog
  1831. /// that contains the initial iterations in the pipeline, and kernel
  1832. /// loop, and the epilogue that contains the code for the final
  1833. /// iterations.
  1834. void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
  1835. // Create a new basic block for the kernel and add it to the CFG.
  1836. MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
  1837. unsigned MaxStageCount = Schedule.getMaxStageCount();
  1838. // Remember the registers that are used in different stages. The index is
  1839. // the iteration, or stage, that the instruction is scheduled in. This is
  1840. // a map between register names in the original block and the names created
  1841. // in each stage of the pipelined loop.
  1842. ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
  1843. InstrMapTy InstrMap;
  1844. SmallVector<MachineBasicBlock *, 4> PrologBBs;
  1845. MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
  1846. assert(PreheaderBB != nullptr &&
  1847. "Need to add code to handle loops w/o preheader");
  1848. // Generate the prolog instructions that set up the pipeline.
  1849. generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
  1850. MF.insert(BB->getIterator(), KernelBB);
  1851. // Rearrange the instructions to generate the new, pipelined loop,
  1852. // and update register names as needed.
  1853. for (int Cycle = Schedule.getFirstCycle(),
  1854. LastCycle = Schedule.getFinalCycle();
  1855. Cycle <= LastCycle; ++Cycle) {
  1856. std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
  1857. // This inner loop schedules each instruction in the cycle.
  1858. for (SUnit *CI : CycleInstrs) {
  1859. if (CI->getInstr()->isPHI())
  1860. continue;
  1861. unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
  1862. MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
  1863. updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
  1864. KernelBB->push_back(NewMI);
  1865. InstrMap[NewMI] = CI->getInstr();
  1866. }
  1867. }
  1868. // Copy any terminator instructions to the new kernel, and update
  1869. // names as needed.
  1870. for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
  1871. E = BB->instr_end();
  1872. I != E; ++I) {
  1873. MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
  1874. updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
  1875. KernelBB->push_back(NewMI);
  1876. InstrMap[NewMI] = &*I;
  1877. }
  1878. KernelBB->transferSuccessors(BB);
  1879. KernelBB->replaceSuccessor(BB, KernelBB);
  1880. generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
  1881. VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
  1882. generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
  1883. InstrMap, MaxStageCount, MaxStageCount, false);
  1884. LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
  1885. SmallVector<MachineBasicBlock *, 4> EpilogBBs;
  1886. // Generate the epilog instructions to complete the pipeline.
  1887. generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
  1888. PrologBBs);
  1889. // We need this step because the register allocation doesn't handle some
  1890. // situations well, so we insert copies to help out.
  1891. splitLifetimes(KernelBB, EpilogBBs, Schedule);
  1892. // Remove dead instructions due to loop induction variables.
  1893. removeDeadInstructions(KernelBB, EpilogBBs);
  1894. // Add branches between prolog and epilog blocks.
  1895. addBranches(*PreheaderBB, PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
  1896. // Remove the original loop since it's no longer referenced.
  1897. for (auto &I : *BB)
  1898. LIS.RemoveMachineInstrFromMaps(I);
  1899. BB->clear();
  1900. BB->eraseFromParent();
  1901. delete[] VRMap;
  1902. }
  1903. /// Generate the pipeline prolog code.
  1904. void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
  1905. MachineBasicBlock *KernelBB,
  1906. ValueMapTy *VRMap,
  1907. MBBVectorTy &PrologBBs) {
  1908. MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
  1909. assert(PreheaderBB != nullptr &&
  1910. "Need to add code to handle loops w/o preheader");
  1911. MachineBasicBlock *PredBB = PreheaderBB;
  1912. InstrMapTy InstrMap;
  1913. // Generate a basic block for each stage, not including the last stage,
  1914. // which will be generated in the kernel. Each basic block may contain
  1915. // instructions from multiple stages/iterations.
  1916. for (unsigned i = 0; i < LastStage; ++i) {
  1917. // Create and insert the prolog basic block prior to the original loop
  1918. // basic block. The original loop is removed later.
  1919. MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
  1920. PrologBBs.push_back(NewBB);
  1921. MF.insert(BB->getIterator(), NewBB);
  1922. NewBB->transferSuccessors(PredBB);
  1923. PredBB->addSuccessor(NewBB);
  1924. PredBB = NewBB;
  1925. // Generate instructions for each appropriate stage. Process instructions
  1926. // in original program order.
  1927. for (int StageNum = i; StageNum >= 0; --StageNum) {
  1928. for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
  1929. BBE = BB->getFirstTerminator();
  1930. BBI != BBE; ++BBI) {
  1931. if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
  1932. if (BBI->isPHI())
  1933. continue;
  1934. MachineInstr *NewMI =
  1935. cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
  1936. updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
  1937. VRMap);
  1938. NewBB->push_back(NewMI);
  1939. InstrMap[NewMI] = &*BBI;
  1940. }
  1941. }
  1942. }
  1943. rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
  1944. LLVM_DEBUG({
  1945. dbgs() << "prolog:\n";
  1946. NewBB->dump();
  1947. });
  1948. }
  1949. PredBB->replaceSuccessor(BB, KernelBB);
  1950. // Check if we need to remove the branch from the preheader to the original
  1951. // loop, and replace it with a branch to the new loop.
  1952. unsigned numBranches = TII->removeBranch(*PreheaderBB);
  1953. if (numBranches) {
  1954. SmallVector<MachineOperand, 0> Cond;
  1955. TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
  1956. }
  1957. }
  1958. /// Generate the pipeline epilog code. The epilog code finishes the iterations
  1959. /// that were started in either the prolog or the kernel. We create a basic
  1960. /// block for each stage that needs to complete.
  1961. void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
  1962. MachineBasicBlock *KernelBB,
  1963. ValueMapTy *VRMap,
  1964. MBBVectorTy &EpilogBBs,
  1965. MBBVectorTy &PrologBBs) {
  1966. // We need to change the branch from the kernel to the first epilog block, so
  1967. // this call to analyze branch uses the kernel rather than the original BB.
  1968. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  1969. SmallVector<MachineOperand, 4> Cond;
  1970. bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
  1971. assert(!checkBranch && "generateEpilog must be able to analyze the branch");
  1972. if (checkBranch)
  1973. return;
  1974. MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
  1975. if (*LoopExitI == KernelBB)
  1976. ++LoopExitI;
  1977. assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
  1978. MachineBasicBlock *LoopExitBB = *LoopExitI;
  1979. MachineBasicBlock *PredBB = KernelBB;
  1980. MachineBasicBlock *EpilogStart = LoopExitBB;
  1981. InstrMapTy InstrMap;
  1982. // Generate a basic block for each stage, not including the last stage,
  1983. // which was generated for the kernel. Each basic block may contain
  1984. // instructions from multiple stages/iterations.
  1985. int EpilogStage = LastStage + 1;
  1986. for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
  1987. MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
  1988. EpilogBBs.push_back(NewBB);
  1989. MF.insert(BB->getIterator(), NewBB);
  1990. PredBB->replaceSuccessor(LoopExitBB, NewBB);
  1991. NewBB->addSuccessor(LoopExitBB);
  1992. if (EpilogStart == LoopExitBB)
  1993. EpilogStart = NewBB;
  1994. // Add instructions to the epilog depending on the current block.
  1995. // Process instructions in original program order.
  1996. for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
  1997. for (auto &BBI : *BB) {
  1998. if (BBI.isPHI())
  1999. continue;
  2000. MachineInstr *In = &BBI;
  2001. if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
  2002. // Instructions with memoperands in the epilog are updated with
  2003. // conservative values.
  2004. MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
  2005. updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
  2006. NewBB->push_back(NewMI);
  2007. InstrMap[NewMI] = In;
  2008. }
  2009. }
  2010. }
  2011. generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
  2012. VRMap, InstrMap, LastStage, EpilogStage, i == 1);
  2013. generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
  2014. InstrMap, LastStage, EpilogStage, i == 1);
  2015. PredBB = NewBB;
  2016. LLVM_DEBUG({
  2017. dbgs() << "epilog:\n";
  2018. NewBB->dump();
  2019. });
  2020. }
  2021. // Fix any Phi nodes in the loop exit block.
  2022. for (MachineInstr &MI : *LoopExitBB) {
  2023. if (!MI.isPHI())
  2024. break;
  2025. for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
  2026. MachineOperand &MO = MI.getOperand(i);
  2027. if (MO.getMBB() == BB)
  2028. MO.setMBB(PredBB);
  2029. }
  2030. }
  2031. // Create a branch to the new epilog from the kernel.
  2032. // Remove the original branch and add a new branch to the epilog.
  2033. TII->removeBranch(*KernelBB);
  2034. TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
  2035. // Add a branch to the loop exit.
  2036. if (EpilogBBs.size() > 0) {
  2037. MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
  2038. SmallVector<MachineOperand, 4> Cond1;
  2039. TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
  2040. }
  2041. }
  2042. /// Replace all uses of FromReg that appear outside the specified
  2043. /// basic block with ToReg.
  2044. static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
  2045. MachineBasicBlock *MBB,
  2046. MachineRegisterInfo &MRI,
  2047. LiveIntervals &LIS) {
  2048. for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
  2049. E = MRI.use_end();
  2050. I != E;) {
  2051. MachineOperand &O = *I;
  2052. ++I;
  2053. if (O.getParent()->getParent() != MBB)
  2054. O.setReg(ToReg);
  2055. }
  2056. if (!LIS.hasInterval(ToReg))
  2057. LIS.createEmptyInterval(ToReg);
  2058. }
  2059. /// Return true if the register has a use that occurs outside the
  2060. /// specified loop.
  2061. static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
  2062. MachineRegisterInfo &MRI) {
  2063. for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
  2064. E = MRI.use_end();
  2065. I != E; ++I)
  2066. if (I->getParent()->getParent() != BB)
  2067. return true;
  2068. return false;
  2069. }
  2070. /// Generate Phis for the specific block in the generated pipelined code.
  2071. /// This function looks at the Phis from the original code to guide the
  2072. /// creation of new Phis.
  2073. void SwingSchedulerDAG::generateExistingPhis(
  2074. MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
  2075. MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
  2076. InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
  2077. bool IsLast) {
  2078. // Compute the stage number for the initial value of the Phi, which
  2079. // comes from the prolog. The prolog to use depends on to which kernel/
  2080. // epilog that we're adding the Phi.
  2081. unsigned PrologStage = 0;
  2082. unsigned PrevStage = 0;
  2083. bool InKernel = (LastStageNum == CurStageNum);
  2084. if (InKernel) {
  2085. PrologStage = LastStageNum - 1;
  2086. PrevStage = CurStageNum;
  2087. } else {
  2088. PrologStage = LastStageNum - (CurStageNum - LastStageNum);
  2089. PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
  2090. }
  2091. for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
  2092. BBE = BB->getFirstNonPHI();
  2093. BBI != BBE; ++BBI) {
  2094. unsigned Def = BBI->getOperand(0).getReg();
  2095. unsigned InitVal = 0;
  2096. unsigned LoopVal = 0;
  2097. getPhiRegs(*BBI, BB, InitVal, LoopVal);
  2098. unsigned PhiOp1 = 0;
  2099. // The Phi value from the loop body typically is defined in the loop, but
  2100. // not always. So, we need to check if the value is defined in the loop.
  2101. unsigned PhiOp2 = LoopVal;
  2102. if (VRMap[LastStageNum].count(LoopVal))
  2103. PhiOp2 = VRMap[LastStageNum][LoopVal];
  2104. int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
  2105. int LoopValStage =
  2106. Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
  2107. unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
  2108. if (NumStages == 0) {
  2109. // We don't need to generate a Phi anymore, but we need to rename any uses
  2110. // of the Phi value.
  2111. unsigned NewReg = VRMap[PrevStage][LoopVal];
  2112. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
  2113. Def, InitVal, NewReg);
  2114. if (VRMap[CurStageNum].count(LoopVal))
  2115. VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
  2116. }
  2117. // Adjust the number of Phis needed depending on the number of prologs left,
  2118. // and the distance from where the Phi is first scheduled. The number of
  2119. // Phis cannot exceed the number of prolog stages. Each stage can
  2120. // potentially define two values.
  2121. unsigned MaxPhis = PrologStage + 2;
  2122. if (!InKernel && (int)PrologStage <= LoopValStage)
  2123. MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
  2124. unsigned NumPhis = std::min(NumStages, MaxPhis);
  2125. unsigned NewReg = 0;
  2126. unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
  2127. // In the epilog, we may need to look back one stage to get the correct
  2128. // Phi name because the epilog and prolog blocks execute the same stage.
  2129. // The correct name is from the previous block only when the Phi has
  2130. // been completely scheduled prior to the epilog, and Phi value is not
  2131. // needed in multiple stages.
  2132. int StageDiff = 0;
  2133. if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
  2134. NumPhis == 1)
  2135. StageDiff = 1;
  2136. // Adjust the computations below when the phi and the loop definition
  2137. // are scheduled in different stages.
  2138. if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
  2139. StageDiff = StageScheduled - LoopValStage;
  2140. for (unsigned np = 0; np < NumPhis; ++np) {
  2141. // If the Phi hasn't been scheduled, then use the initial Phi operand
  2142. // value. Otherwise, use the scheduled version of the instruction. This
  2143. // is a little complicated when a Phi references another Phi.
  2144. if (np > PrologStage || StageScheduled >= (int)LastStageNum)
  2145. PhiOp1 = InitVal;
  2146. // Check if the Phi has already been scheduled in a prolog stage.
  2147. else if (PrologStage >= AccessStage + StageDiff + np &&
  2148. VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
  2149. PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
  2150. // Check if the Phi has already been scheduled, but the loop instruction
  2151. // is either another Phi, or doesn't occur in the loop.
  2152. else if (PrologStage >= AccessStage + StageDiff + np) {
  2153. // If the Phi references another Phi, we need to examine the other
  2154. // Phi to get the correct value.
  2155. PhiOp1 = LoopVal;
  2156. MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
  2157. int Indirects = 1;
  2158. while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
  2159. int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
  2160. if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
  2161. PhiOp1 = getInitPhiReg(*InstOp1, BB);
  2162. else
  2163. PhiOp1 = getLoopPhiReg(*InstOp1, BB);
  2164. InstOp1 = MRI.getVRegDef(PhiOp1);
  2165. int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
  2166. int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
  2167. if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
  2168. VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
  2169. PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
  2170. break;
  2171. }
  2172. ++Indirects;
  2173. }
  2174. } else
  2175. PhiOp1 = InitVal;
  2176. // If this references a generated Phi in the kernel, get the Phi operand
  2177. // from the incoming block.
  2178. if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
  2179. if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
  2180. PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
  2181. MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
  2182. bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
  2183. // In the epilog, a map lookup is needed to get the value from the kernel,
  2184. // or previous epilog block. How is does this depends on if the
  2185. // instruction is scheduled in the previous block.
  2186. if (!InKernel) {
  2187. int StageDiffAdj = 0;
  2188. if (LoopValStage != -1 && StageScheduled > LoopValStage)
  2189. StageDiffAdj = StageScheduled - LoopValStage;
  2190. // Use the loop value defined in the kernel, unless the kernel
  2191. // contains the last definition of the Phi.
  2192. if (np == 0 && PrevStage == LastStageNum &&
  2193. (StageScheduled != 0 || LoopValStage != 0) &&
  2194. VRMap[PrevStage - StageDiffAdj].count(LoopVal))
  2195. PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
  2196. // Use the value defined by the Phi. We add one because we switch
  2197. // from looking at the loop value to the Phi definition.
  2198. else if (np > 0 && PrevStage == LastStageNum &&
  2199. VRMap[PrevStage - np + 1].count(Def))
  2200. PhiOp2 = VRMap[PrevStage - np + 1][Def];
  2201. // Use the loop value defined in the kernel.
  2202. else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
  2203. VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
  2204. PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
  2205. // Use the value defined by the Phi, unless we're generating the first
  2206. // epilog and the Phi refers to a Phi in a different stage.
  2207. else if (VRMap[PrevStage - np].count(Def) &&
  2208. (!LoopDefIsPhi || PrevStage != LastStageNum))
  2209. PhiOp2 = VRMap[PrevStage - np][Def];
  2210. }
  2211. // Check if we can reuse an existing Phi. This occurs when a Phi
  2212. // references another Phi, and the other Phi is scheduled in an
  2213. // earlier stage. We can try to reuse an existing Phi up until the last
  2214. // stage of the current Phi.
  2215. if (LoopDefIsPhi) {
  2216. if (static_cast<int>(PrologStage - np) >= StageScheduled) {
  2217. int LVNumStages = Schedule.getStagesForPhi(LoopVal);
  2218. int StageDiff = (StageScheduled - LoopValStage);
  2219. LVNumStages -= StageDiff;
  2220. // Make sure the loop value Phi has been processed already.
  2221. if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
  2222. NewReg = PhiOp2;
  2223. unsigned ReuseStage = CurStageNum;
  2224. if (Schedule.isLoopCarried(this, *PhiInst))
  2225. ReuseStage -= LVNumStages;
  2226. // Check if the Phi to reuse has been generated yet. If not, then
  2227. // there is nothing to reuse.
  2228. if (VRMap[ReuseStage - np].count(LoopVal)) {
  2229. NewReg = VRMap[ReuseStage - np][LoopVal];
  2230. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2231. &*BBI, Def, NewReg);
  2232. // Update the map with the new Phi name.
  2233. VRMap[CurStageNum - np][Def] = NewReg;
  2234. PhiOp2 = NewReg;
  2235. if (VRMap[LastStageNum - np - 1].count(LoopVal))
  2236. PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
  2237. if (IsLast && np == NumPhis - 1)
  2238. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  2239. continue;
  2240. }
  2241. }
  2242. }
  2243. if (InKernel && StageDiff > 0 &&
  2244. VRMap[CurStageNum - StageDiff - np].count(LoopVal))
  2245. PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
  2246. }
  2247. const TargetRegisterClass *RC = MRI.getRegClass(Def);
  2248. NewReg = MRI.createVirtualRegister(RC);
  2249. MachineInstrBuilder NewPhi =
  2250. BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
  2251. TII->get(TargetOpcode::PHI), NewReg);
  2252. NewPhi.addReg(PhiOp1).addMBB(BB1);
  2253. NewPhi.addReg(PhiOp2).addMBB(BB2);
  2254. if (np == 0)
  2255. InstrMap[NewPhi] = &*BBI;
  2256. // We define the Phis after creating the new pipelined code, so
  2257. // we need to rename the Phi values in scheduled instructions.
  2258. unsigned PrevReg = 0;
  2259. if (InKernel && VRMap[PrevStage - np].count(LoopVal))
  2260. PrevReg = VRMap[PrevStage - np][LoopVal];
  2261. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
  2262. Def, NewReg, PrevReg);
  2263. // If the Phi has been scheduled, use the new name for rewriting.
  2264. if (VRMap[CurStageNum - np].count(Def)) {
  2265. unsigned R = VRMap[CurStageNum - np][Def];
  2266. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
  2267. R, NewReg);
  2268. }
  2269. // Check if we need to rename any uses that occurs after the loop. The
  2270. // register to replace depends on whether the Phi is scheduled in the
  2271. // epilog.
  2272. if (IsLast && np == NumPhis - 1)
  2273. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  2274. // In the kernel, a dependent Phi uses the value from this Phi.
  2275. if (InKernel)
  2276. PhiOp2 = NewReg;
  2277. // Update the map with the new Phi name.
  2278. VRMap[CurStageNum - np][Def] = NewReg;
  2279. }
  2280. while (NumPhis++ < NumStages) {
  2281. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
  2282. &*BBI, Def, NewReg, 0);
  2283. }
  2284. // Check if we need to rename a Phi that has been eliminated due to
  2285. // scheduling.
  2286. if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
  2287. replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
  2288. }
  2289. }
  2290. /// Generate Phis for the specified block in the generated pipelined code.
  2291. /// These are new Phis needed because the definition is scheduled after the
  2292. /// use in the pipelined sequence.
  2293. void SwingSchedulerDAG::generatePhis(
  2294. MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
  2295. MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
  2296. InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
  2297. bool IsLast) {
  2298. // Compute the stage number that contains the initial Phi value, and
  2299. // the Phi from the previous stage.
  2300. unsigned PrologStage = 0;
  2301. unsigned PrevStage = 0;
  2302. unsigned StageDiff = CurStageNum - LastStageNum;
  2303. bool InKernel = (StageDiff == 0);
  2304. if (InKernel) {
  2305. PrologStage = LastStageNum - 1;
  2306. PrevStage = CurStageNum;
  2307. } else {
  2308. PrologStage = LastStageNum - StageDiff;
  2309. PrevStage = LastStageNum + StageDiff - 1;
  2310. }
  2311. for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
  2312. BBE = BB->instr_end();
  2313. BBI != BBE; ++BBI) {
  2314. for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
  2315. MachineOperand &MO = BBI->getOperand(i);
  2316. if (!MO.isReg() || !MO.isDef() ||
  2317. !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  2318. continue;
  2319. int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
  2320. assert(StageScheduled != -1 && "Expecting scheduled instruction.");
  2321. unsigned Def = MO.getReg();
  2322. unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
  2323. // An instruction scheduled in stage 0 and is used after the loop
  2324. // requires a phi in the epilog for the last definition from either
  2325. // the kernel or prolog.
  2326. if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
  2327. hasUseAfterLoop(Def, BB, MRI))
  2328. NumPhis = 1;
  2329. if (!InKernel && (unsigned)StageScheduled > PrologStage)
  2330. continue;
  2331. unsigned PhiOp2 = VRMap[PrevStage][Def];
  2332. if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
  2333. if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
  2334. PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
  2335. // The number of Phis can't exceed the number of prolog stages. The
  2336. // prolog stage number is zero based.
  2337. if (NumPhis > PrologStage + 1 - StageScheduled)
  2338. NumPhis = PrologStage + 1 - StageScheduled;
  2339. for (unsigned np = 0; np < NumPhis; ++np) {
  2340. unsigned PhiOp1 = VRMap[PrologStage][Def];
  2341. if (np <= PrologStage)
  2342. PhiOp1 = VRMap[PrologStage - np][Def];
  2343. if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
  2344. if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
  2345. PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
  2346. if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
  2347. PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
  2348. }
  2349. if (!InKernel)
  2350. PhiOp2 = VRMap[PrevStage - np][Def];
  2351. const TargetRegisterClass *RC = MRI.getRegClass(Def);
  2352. unsigned NewReg = MRI.createVirtualRegister(RC);
  2353. MachineInstrBuilder NewPhi =
  2354. BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
  2355. TII->get(TargetOpcode::PHI), NewReg);
  2356. NewPhi.addReg(PhiOp1).addMBB(BB1);
  2357. NewPhi.addReg(PhiOp2).addMBB(BB2);
  2358. if (np == 0)
  2359. InstrMap[NewPhi] = &*BBI;
  2360. // Rewrite uses and update the map. The actions depend upon whether
  2361. // we generating code for the kernel or epilog blocks.
  2362. if (InKernel) {
  2363. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2364. &*BBI, PhiOp1, NewReg);
  2365. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2366. &*BBI, PhiOp2, NewReg);
  2367. PhiOp2 = NewReg;
  2368. VRMap[PrevStage - np - 1][Def] = NewReg;
  2369. } else {
  2370. VRMap[CurStageNum - np][Def] = NewReg;
  2371. if (np == NumPhis - 1)
  2372. rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
  2373. &*BBI, Def, NewReg);
  2374. }
  2375. if (IsLast && np == NumPhis - 1)
  2376. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  2377. }
  2378. }
  2379. }
  2380. }
  2381. /// Remove instructions that generate values with no uses.
  2382. /// Typically, these are induction variable operations that generate values
  2383. /// used in the loop itself. A dead instruction has a definition with
  2384. /// no uses, or uses that occur in the original loop only.
  2385. void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
  2386. MBBVectorTy &EpilogBBs) {
  2387. // For each epilog block, check that the value defined by each instruction
  2388. // is used. If not, delete it.
  2389. for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
  2390. MBE = EpilogBBs.rend();
  2391. MBB != MBE; ++MBB)
  2392. for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
  2393. ME = (*MBB)->instr_rend();
  2394. MI != ME;) {
  2395. // From DeadMachineInstructionElem. Don't delete inline assembly.
  2396. if (MI->isInlineAsm()) {
  2397. ++MI;
  2398. continue;
  2399. }
  2400. bool SawStore = false;
  2401. // Check if it's safe to remove the instruction due to side effects.
  2402. // We can, and want to, remove Phis here.
  2403. if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
  2404. ++MI;
  2405. continue;
  2406. }
  2407. bool used = true;
  2408. for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
  2409. MOE = MI->operands_end();
  2410. MOI != MOE; ++MOI) {
  2411. if (!MOI->isReg() || !MOI->isDef())
  2412. continue;
  2413. unsigned reg = MOI->getReg();
  2414. // Assume physical registers are used, unless they are marked dead.
  2415. if (TargetRegisterInfo::isPhysicalRegister(reg)) {
  2416. used = !MOI->isDead();
  2417. if (used)
  2418. break;
  2419. continue;
  2420. }
  2421. unsigned realUses = 0;
  2422. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
  2423. EI = MRI.use_end();
  2424. UI != EI; ++UI) {
  2425. // Check if there are any uses that occur only in the original
  2426. // loop. If so, that's not a real use.
  2427. if (UI->getParent()->getParent() != BB) {
  2428. realUses++;
  2429. used = true;
  2430. break;
  2431. }
  2432. }
  2433. if (realUses > 0)
  2434. break;
  2435. used = false;
  2436. }
  2437. if (!used) {
  2438. LIS.RemoveMachineInstrFromMaps(*MI);
  2439. MI++->eraseFromParent();
  2440. continue;
  2441. }
  2442. ++MI;
  2443. }
  2444. // In the kernel block, check if we can remove a Phi that generates a value
  2445. // used in an instruction removed in the epilog block.
  2446. for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
  2447. BBE = KernelBB->getFirstNonPHI();
  2448. BBI != BBE;) {
  2449. MachineInstr *MI = &*BBI;
  2450. ++BBI;
  2451. unsigned reg = MI->getOperand(0).getReg();
  2452. if (MRI.use_begin(reg) == MRI.use_end()) {
  2453. LIS.RemoveMachineInstrFromMaps(*MI);
  2454. MI->eraseFromParent();
  2455. }
  2456. }
  2457. }
  2458. /// For loop carried definitions, we split the lifetime of a virtual register
  2459. /// that has uses past the definition in the next iteration. A copy with a new
  2460. /// virtual register is inserted before the definition, which helps with
  2461. /// generating a better register assignment.
  2462. ///
  2463. /// v1 = phi(a, v2) v1 = phi(a, v2)
  2464. /// v2 = phi(b, v3) v2 = phi(b, v3)
  2465. /// v3 = .. v4 = copy v1
  2466. /// .. = V1 v3 = ..
  2467. /// .. = v4
  2468. void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
  2469. MBBVectorTy &EpilogBBs,
  2470. SMSchedule &Schedule) {
  2471. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2472. for (auto &PHI : KernelBB->phis()) {
  2473. unsigned Def = PHI.getOperand(0).getReg();
  2474. // Check for any Phi definition that used as an operand of another Phi
  2475. // in the same block.
  2476. for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
  2477. E = MRI.use_instr_end();
  2478. I != E; ++I) {
  2479. if (I->isPHI() && I->getParent() == KernelBB) {
  2480. // Get the loop carried definition.
  2481. unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
  2482. if (!LCDef)
  2483. continue;
  2484. MachineInstr *MI = MRI.getVRegDef(LCDef);
  2485. if (!MI || MI->getParent() != KernelBB || MI->isPHI())
  2486. continue;
  2487. // Search through the rest of the block looking for uses of the Phi
  2488. // definition. If one occurs, then split the lifetime.
  2489. unsigned SplitReg = 0;
  2490. for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
  2491. KernelBB->instr_end()))
  2492. if (BBJ.readsRegister(Def)) {
  2493. // We split the lifetime when we find the first use.
  2494. if (SplitReg == 0) {
  2495. SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
  2496. BuildMI(*KernelBB, MI, MI->getDebugLoc(),
  2497. TII->get(TargetOpcode::COPY), SplitReg)
  2498. .addReg(Def);
  2499. }
  2500. BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
  2501. }
  2502. if (!SplitReg)
  2503. continue;
  2504. // Search through each of the epilog blocks for any uses to be renamed.
  2505. for (auto &Epilog : EpilogBBs)
  2506. for (auto &I : *Epilog)
  2507. if (I.readsRegister(Def))
  2508. I.substituteRegister(Def, SplitReg, 0, *TRI);
  2509. break;
  2510. }
  2511. }
  2512. }
  2513. }
  2514. /// Remove the incoming block from the Phis in a basic block.
  2515. static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
  2516. for (MachineInstr &MI : *BB) {
  2517. if (!MI.isPHI())
  2518. break;
  2519. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
  2520. if (MI.getOperand(i + 1).getMBB() == Incoming) {
  2521. MI.RemoveOperand(i + 1);
  2522. MI.RemoveOperand(i);
  2523. break;
  2524. }
  2525. }
  2526. }
  2527. /// Create branches from each prolog basic block to the appropriate epilog
  2528. /// block. These edges are needed if the loop ends before reaching the
  2529. /// kernel.
  2530. void SwingSchedulerDAG::addBranches(MachineBasicBlock &PreheaderBB,
  2531. MBBVectorTy &PrologBBs,
  2532. MachineBasicBlock *KernelBB,
  2533. MBBVectorTy &EpilogBBs,
  2534. SMSchedule &Schedule, ValueMapTy *VRMap) {
  2535. assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
  2536. MachineInstr *IndVar = Pass.LI.LoopInductionVar;
  2537. MachineInstr *Cmp = Pass.LI.LoopCompare;
  2538. MachineBasicBlock *LastPro = KernelBB;
  2539. MachineBasicBlock *LastEpi = KernelBB;
  2540. // Start from the blocks connected to the kernel and work "out"
  2541. // to the first prolog and the last epilog blocks.
  2542. SmallVector<MachineInstr *, 4> PrevInsts;
  2543. unsigned MaxIter = PrologBBs.size() - 1;
  2544. unsigned LC = UINT_MAX;
  2545. unsigned LCMin = UINT_MAX;
  2546. for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
  2547. // Add branches to the prolog that go to the corresponding
  2548. // epilog, and the fall-thru prolog/kernel block.
  2549. MachineBasicBlock *Prolog = PrologBBs[j];
  2550. MachineBasicBlock *Epilog = EpilogBBs[i];
  2551. // We've executed one iteration, so decrement the loop count and check for
  2552. // the loop end.
  2553. SmallVector<MachineOperand, 4> Cond;
  2554. // Check if the LOOP0 has already been removed. If so, then there is no need
  2555. // to reduce the trip count.
  2556. if (LC != 0)
  2557. LC = TII->reduceLoopCount(*Prolog, PreheaderBB, IndVar, *Cmp, Cond,
  2558. PrevInsts, j, MaxIter);
  2559. // Record the value of the first trip count, which is used to determine if
  2560. // branches and blocks can be removed for constant trip counts.
  2561. if (LCMin == UINT_MAX)
  2562. LCMin = LC;
  2563. unsigned numAdded = 0;
  2564. if (TargetRegisterInfo::isVirtualRegister(LC)) {
  2565. Prolog->addSuccessor(Epilog);
  2566. numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
  2567. } else if (j >= LCMin) {
  2568. Prolog->addSuccessor(Epilog);
  2569. Prolog->removeSuccessor(LastPro);
  2570. LastEpi->removeSuccessor(Epilog);
  2571. numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
  2572. removePhis(Epilog, LastEpi);
  2573. // Remove the blocks that are no longer referenced.
  2574. if (LastPro != LastEpi) {
  2575. LastEpi->clear();
  2576. LastEpi->eraseFromParent();
  2577. }
  2578. LastPro->clear();
  2579. LastPro->eraseFromParent();
  2580. } else {
  2581. numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
  2582. removePhis(Epilog, Prolog);
  2583. }
  2584. LastPro = Prolog;
  2585. LastEpi = Epilog;
  2586. for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
  2587. E = Prolog->instr_rend();
  2588. I != E && numAdded > 0; ++I, --numAdded)
  2589. updateInstruction(&*I, false, j, 0, Schedule, VRMap);
  2590. }
  2591. }
  2592. /// Return true if we can compute the amount the instruction changes
  2593. /// during each iteration. Set Delta to the amount of the change.
  2594. bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
  2595. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2596. const MachineOperand *BaseOp;
  2597. int64_t Offset;
  2598. if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
  2599. return false;
  2600. if (!BaseOp->isReg())
  2601. return false;
  2602. unsigned BaseReg = BaseOp->getReg();
  2603. MachineRegisterInfo &MRI = MF.getRegInfo();
  2604. // Check if there is a Phi. If so, get the definition in the loop.
  2605. MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
  2606. if (BaseDef && BaseDef->isPHI()) {
  2607. BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
  2608. BaseDef = MRI.getVRegDef(BaseReg);
  2609. }
  2610. if (!BaseDef)
  2611. return false;
  2612. int D = 0;
  2613. if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
  2614. return false;
  2615. Delta = D;
  2616. return true;
  2617. }
  2618. /// Update the memory operand with a new offset when the pipeliner
  2619. /// generates a new copy of the instruction that refers to a
  2620. /// different memory location.
  2621. void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
  2622. MachineInstr &OldMI, unsigned Num) {
  2623. if (Num == 0)
  2624. return;
  2625. // If the instruction has memory operands, then adjust the offset
  2626. // when the instruction appears in different stages.
  2627. if (NewMI.memoperands_empty())
  2628. return;
  2629. SmallVector<MachineMemOperand *, 2> NewMMOs;
  2630. for (MachineMemOperand *MMO : NewMI.memoperands()) {
  2631. // TODO: Figure out whether isAtomic is really necessary (see D57601).
  2632. if (MMO->isVolatile() || MMO->isAtomic() ||
  2633. (MMO->isInvariant() && MMO->isDereferenceable()) ||
  2634. (!MMO->getValue())) {
  2635. NewMMOs.push_back(MMO);
  2636. continue;
  2637. }
  2638. unsigned Delta;
  2639. if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
  2640. int64_t AdjOffset = Delta * Num;
  2641. NewMMOs.push_back(
  2642. MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
  2643. } else {
  2644. NewMMOs.push_back(
  2645. MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
  2646. }
  2647. }
  2648. NewMI.setMemRefs(MF, NewMMOs);
  2649. }
  2650. /// Clone the instruction for the new pipelined loop and update the
  2651. /// memory operands, if needed.
  2652. MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
  2653. unsigned CurStageNum,
  2654. unsigned InstStageNum) {
  2655. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  2656. // Check for tied operands in inline asm instructions. This should be handled
  2657. // elsewhere, but I'm not sure of the best solution.
  2658. if (OldMI->isInlineAsm())
  2659. for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
  2660. const auto &MO = OldMI->getOperand(i);
  2661. if (MO.isReg() && MO.isUse())
  2662. break;
  2663. unsigned UseIdx;
  2664. if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
  2665. NewMI->tieOperands(i, UseIdx);
  2666. }
  2667. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  2668. return NewMI;
  2669. }
  2670. /// Clone the instruction for the new pipelined loop. If needed, this
  2671. /// function updates the instruction using the values saved in the
  2672. /// InstrChanges structure.
  2673. MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
  2674. unsigned CurStageNum,
  2675. unsigned InstStageNum,
  2676. SMSchedule &Schedule) {
  2677. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  2678. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  2679. InstrChanges.find(getSUnit(OldMI));
  2680. if (It != InstrChanges.end()) {
  2681. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  2682. unsigned BasePos, OffsetPos;
  2683. if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
  2684. return nullptr;
  2685. int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
  2686. MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
  2687. if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
  2688. NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
  2689. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  2690. }
  2691. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  2692. return NewMI;
  2693. }
  2694. /// Update the machine instruction with new virtual registers. This
  2695. /// function may change the defintions and/or uses.
  2696. void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
  2697. unsigned CurStageNum,
  2698. unsigned InstrStageNum,
  2699. SMSchedule &Schedule,
  2700. ValueMapTy *VRMap) {
  2701. for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
  2702. MachineOperand &MO = NewMI->getOperand(i);
  2703. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  2704. continue;
  2705. unsigned reg = MO.getReg();
  2706. if (MO.isDef()) {
  2707. // Create a new virtual register for the definition.
  2708. const TargetRegisterClass *RC = MRI.getRegClass(reg);
  2709. unsigned NewReg = MRI.createVirtualRegister(RC);
  2710. MO.setReg(NewReg);
  2711. VRMap[CurStageNum][reg] = NewReg;
  2712. if (LastDef)
  2713. replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
  2714. } else if (MO.isUse()) {
  2715. MachineInstr *Def = MRI.getVRegDef(reg);
  2716. // Compute the stage that contains the last definition for instruction.
  2717. int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
  2718. unsigned StageNum = CurStageNum;
  2719. if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
  2720. // Compute the difference in stages between the defintion and the use.
  2721. unsigned StageDiff = (InstrStageNum - DefStageNum);
  2722. // Make an adjustment to get the last definition.
  2723. StageNum -= StageDiff;
  2724. }
  2725. if (VRMap[StageNum].count(reg))
  2726. MO.setReg(VRMap[StageNum][reg]);
  2727. }
  2728. }
  2729. }
  2730. /// Return the instruction in the loop that defines the register.
  2731. /// If the definition is a Phi, then follow the Phi operand to
  2732. /// the instruction in the loop.
  2733. MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
  2734. SmallPtrSet<MachineInstr *, 8> Visited;
  2735. MachineInstr *Def = MRI.getVRegDef(Reg);
  2736. while (Def->isPHI()) {
  2737. if (!Visited.insert(Def).second)
  2738. break;
  2739. for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
  2740. if (Def->getOperand(i + 1).getMBB() == BB) {
  2741. Def = MRI.getVRegDef(Def->getOperand(i).getReg());
  2742. break;
  2743. }
  2744. }
  2745. return Def;
  2746. }
  2747. /// Return the new name for the value from the previous stage.
  2748. unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
  2749. unsigned LoopVal, unsigned LoopStage,
  2750. ValueMapTy *VRMap,
  2751. MachineBasicBlock *BB) {
  2752. unsigned PrevVal = 0;
  2753. if (StageNum > PhiStage) {
  2754. MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
  2755. if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
  2756. // The name is defined in the previous stage.
  2757. PrevVal = VRMap[StageNum - 1][LoopVal];
  2758. else if (VRMap[StageNum].count(LoopVal))
  2759. // The previous name is defined in the current stage when the instruction
  2760. // order is swapped.
  2761. PrevVal = VRMap[StageNum][LoopVal];
  2762. else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
  2763. // The loop value hasn't yet been scheduled.
  2764. PrevVal = LoopVal;
  2765. else if (StageNum == PhiStage + 1)
  2766. // The loop value is another phi, which has not been scheduled.
  2767. PrevVal = getInitPhiReg(*LoopInst, BB);
  2768. else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
  2769. // The loop value is another phi, which has been scheduled.
  2770. PrevVal =
  2771. getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
  2772. LoopStage, VRMap, BB);
  2773. }
  2774. return PrevVal;
  2775. }
  2776. /// Rewrite the Phi values in the specified block to use the mappings
  2777. /// from the initial operand. Once the Phi is scheduled, we switch
  2778. /// to using the loop value instead of the Phi value, so those names
  2779. /// do not need to be rewritten.
  2780. void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
  2781. unsigned StageNum,
  2782. SMSchedule &Schedule,
  2783. ValueMapTy *VRMap,
  2784. InstrMapTy &InstrMap) {
  2785. for (auto &PHI : BB->phis()) {
  2786. unsigned InitVal = 0;
  2787. unsigned LoopVal = 0;
  2788. getPhiRegs(PHI, BB, InitVal, LoopVal);
  2789. unsigned PhiDef = PHI.getOperand(0).getReg();
  2790. unsigned PhiStage =
  2791. (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
  2792. unsigned LoopStage =
  2793. (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
  2794. unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
  2795. if (NumPhis > StageNum)
  2796. NumPhis = StageNum;
  2797. for (unsigned np = 0; np <= NumPhis; ++np) {
  2798. unsigned NewVal =
  2799. getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
  2800. if (!NewVal)
  2801. NewVal = InitVal;
  2802. rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
  2803. PhiDef, NewVal);
  2804. }
  2805. }
  2806. }
  2807. /// Rewrite a previously scheduled instruction to use the register value
  2808. /// from the new instruction. Make sure the instruction occurs in the
  2809. /// basic block, and we don't change the uses in the new instruction.
  2810. void SwingSchedulerDAG::rewriteScheduledInstr(
  2811. MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
  2812. unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
  2813. unsigned NewReg, unsigned PrevReg) {
  2814. bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
  2815. int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
  2816. // Rewrite uses that have been scheduled already to use the new
  2817. // Phi register.
  2818. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
  2819. EI = MRI.use_end();
  2820. UI != EI;) {
  2821. MachineOperand &UseOp = *UI;
  2822. MachineInstr *UseMI = UseOp.getParent();
  2823. ++UI;
  2824. if (UseMI->getParent() != BB)
  2825. continue;
  2826. if (UseMI->isPHI()) {
  2827. if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
  2828. continue;
  2829. if (getLoopPhiReg(*UseMI, BB) != OldReg)
  2830. continue;
  2831. }
  2832. InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
  2833. assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
  2834. SUnit *OrigMISU = getSUnit(OrigInstr->second);
  2835. int StageSched = Schedule.stageScheduled(OrigMISU);
  2836. int CycleSched = Schedule.cycleScheduled(OrigMISU);
  2837. unsigned ReplaceReg = 0;
  2838. // This is the stage for the scheduled instruction.
  2839. if (StagePhi == StageSched && Phi->isPHI()) {
  2840. int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
  2841. if (PrevReg && InProlog)
  2842. ReplaceReg = PrevReg;
  2843. else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
  2844. (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
  2845. ReplaceReg = PrevReg;
  2846. else
  2847. ReplaceReg = NewReg;
  2848. }
  2849. // The scheduled instruction occurs before the scheduled Phi, and the
  2850. // Phi is not loop carried.
  2851. if (!InProlog && StagePhi + 1 == StageSched &&
  2852. !Schedule.isLoopCarried(this, *Phi))
  2853. ReplaceReg = NewReg;
  2854. if (StagePhi > StageSched && Phi->isPHI())
  2855. ReplaceReg = NewReg;
  2856. if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
  2857. ReplaceReg = NewReg;
  2858. if (ReplaceReg) {
  2859. MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
  2860. UseOp.setReg(ReplaceReg);
  2861. }
  2862. }
  2863. }
  2864. /// Check if we can change the instruction to use an offset value from the
  2865. /// previous iteration. If so, return true and set the base and offset values
  2866. /// so that we can rewrite the load, if necessary.
  2867. /// v1 = Phi(v0, v3)
  2868. /// v2 = load v1, 0
  2869. /// v3 = post_store v1, 4, x
  2870. /// This function enables the load to be rewritten as v2 = load v3, 4.
  2871. bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
  2872. unsigned &BasePos,
  2873. unsigned &OffsetPos,
  2874. unsigned &NewBase,
  2875. int64_t &Offset) {
  2876. // Get the load instruction.
  2877. if (TII->isPostIncrement(*MI))
  2878. return false;
  2879. unsigned BasePosLd, OffsetPosLd;
  2880. if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
  2881. return false;
  2882. unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
  2883. // Look for the Phi instruction.
  2884. MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
  2885. MachineInstr *Phi = MRI.getVRegDef(BaseReg);
  2886. if (!Phi || !Phi->isPHI())
  2887. return false;
  2888. // Get the register defined in the loop block.
  2889. unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
  2890. if (!PrevReg)
  2891. return false;
  2892. // Check for the post-increment load/store instruction.
  2893. MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
  2894. if (!PrevDef || PrevDef == MI)
  2895. return false;
  2896. if (!TII->isPostIncrement(*PrevDef))
  2897. return false;
  2898. unsigned BasePos1 = 0, OffsetPos1 = 0;
  2899. if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
  2900. return false;
  2901. // Make sure that the instructions do not access the same memory location in
  2902. // the next iteration.
  2903. int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
  2904. int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
  2905. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  2906. NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
  2907. bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
  2908. MF.DeleteMachineInstr(NewMI);
  2909. if (!Disjoint)
  2910. return false;
  2911. // Set the return value once we determine that we return true.
  2912. BasePos = BasePosLd;
  2913. OffsetPos = OffsetPosLd;
  2914. NewBase = PrevReg;
  2915. Offset = StoreOffset;
  2916. return true;
  2917. }
  2918. /// Apply changes to the instruction if needed. The changes are need
  2919. /// to improve the scheduling and depend up on the final schedule.
  2920. void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
  2921. SMSchedule &Schedule) {
  2922. SUnit *SU = getSUnit(MI);
  2923. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  2924. InstrChanges.find(SU);
  2925. if (It != InstrChanges.end()) {
  2926. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  2927. unsigned BasePos, OffsetPos;
  2928. if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  2929. return;
  2930. unsigned BaseReg = MI->getOperand(BasePos).getReg();
  2931. MachineInstr *LoopDef = findDefInLoop(BaseReg);
  2932. int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
  2933. int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
  2934. int BaseStageNum = Schedule.stageScheduled(SU);
  2935. int BaseCycleNum = Schedule.cycleScheduled(SU);
  2936. if (BaseStageNum < DefStageNum) {
  2937. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  2938. int OffsetDiff = DefStageNum - BaseStageNum;
  2939. if (DefCycleNum < BaseCycleNum) {
  2940. NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
  2941. if (OffsetDiff > 0)
  2942. --OffsetDiff;
  2943. }
  2944. int64_t NewOffset =
  2945. MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
  2946. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  2947. SU->setInstr(NewMI);
  2948. MISUnitMap[NewMI] = SU;
  2949. NewMIs.insert(NewMI);
  2950. }
  2951. }
  2952. }
  2953. /// Return true for an order or output dependence that is loop carried
  2954. /// potentially. A dependence is loop carried if the destination defines a valu
  2955. /// that may be used or defined by the source in a subsequent iteration.
  2956. bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
  2957. bool isSucc) {
  2958. if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
  2959. Dep.isArtificial())
  2960. return false;
  2961. if (!SwpPruneLoopCarried)
  2962. return true;
  2963. if (Dep.getKind() == SDep::Output)
  2964. return true;
  2965. MachineInstr *SI = Source->getInstr();
  2966. MachineInstr *DI = Dep.getSUnit()->getInstr();
  2967. if (!isSucc)
  2968. std::swap(SI, DI);
  2969. assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
  2970. // Assume ordered loads and stores may have a loop carried dependence.
  2971. if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
  2972. SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
  2973. SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
  2974. return true;
  2975. // Only chain dependences between a load and store can be loop carried.
  2976. if (!DI->mayStore() || !SI->mayLoad())
  2977. return false;
  2978. unsigned DeltaS, DeltaD;
  2979. if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
  2980. return true;
  2981. const MachineOperand *BaseOpS, *BaseOpD;
  2982. int64_t OffsetS, OffsetD;
  2983. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2984. if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, TRI) ||
  2985. !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, TRI))
  2986. return true;
  2987. if (!BaseOpS->isIdenticalTo(*BaseOpD))
  2988. return true;
  2989. // Check that the base register is incremented by a constant value for each
  2990. // iteration.
  2991. MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
  2992. if (!Def || !Def->isPHI())
  2993. return true;
  2994. unsigned InitVal = 0;
  2995. unsigned LoopVal = 0;
  2996. getPhiRegs(*Def, BB, InitVal, LoopVal);
  2997. MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
  2998. int D = 0;
  2999. if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
  3000. return true;
  3001. uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
  3002. uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
  3003. // This is the main test, which checks the offset values and the loop
  3004. // increment value to determine if the accesses may be loop carried.
  3005. if (AccessSizeS == MemoryLocation::UnknownSize ||
  3006. AccessSizeD == MemoryLocation::UnknownSize)
  3007. return true;
  3008. if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
  3009. return true;
  3010. return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
  3011. }
  3012. void SwingSchedulerDAG::postprocessDAG() {
  3013. for (auto &M : Mutations)
  3014. M->apply(this);
  3015. }
  3016. /// Try to schedule the node at the specified StartCycle and continue
  3017. /// until the node is schedule or the EndCycle is reached. This function
  3018. /// returns true if the node is scheduled. This routine may search either
  3019. /// forward or backward for a place to insert the instruction based upon
  3020. /// the relative values of StartCycle and EndCycle.
  3021. bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
  3022. bool forward = true;
  3023. LLVM_DEBUG({
  3024. dbgs() << "Trying to insert node between " << StartCycle << " and "
  3025. << EndCycle << " II: " << II << "\n";
  3026. });
  3027. if (StartCycle > EndCycle)
  3028. forward = false;
  3029. // The terminating condition depends on the direction.
  3030. int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
  3031. for (int curCycle = StartCycle; curCycle != termCycle;
  3032. forward ? ++curCycle : --curCycle) {
  3033. // Add the already scheduled instructions at the specified cycle to the
  3034. // DFA.
  3035. ProcItinResources.clearResources();
  3036. for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
  3037. checkCycle <= LastCycle; checkCycle += II) {
  3038. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
  3039. for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
  3040. E = cycleInstrs.end();
  3041. I != E; ++I) {
  3042. if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
  3043. continue;
  3044. assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) &&
  3045. "These instructions have already been scheduled.");
  3046. ProcItinResources.reserveResources(*(*I)->getInstr());
  3047. }
  3048. }
  3049. if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
  3050. ProcItinResources.canReserveResources(*SU->getInstr())) {
  3051. LLVM_DEBUG({
  3052. dbgs() << "\tinsert at cycle " << curCycle << " ";
  3053. SU->getInstr()->dump();
  3054. });
  3055. ScheduledInstrs[curCycle].push_back(SU);
  3056. InstrToCycle.insert(std::make_pair(SU, curCycle));
  3057. if (curCycle > LastCycle)
  3058. LastCycle = curCycle;
  3059. if (curCycle < FirstCycle)
  3060. FirstCycle = curCycle;
  3061. return true;
  3062. }
  3063. LLVM_DEBUG({
  3064. dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
  3065. SU->getInstr()->dump();
  3066. });
  3067. }
  3068. return false;
  3069. }
  3070. // Return the cycle of the earliest scheduled instruction in the chain.
  3071. int SMSchedule::earliestCycleInChain(const SDep &Dep) {
  3072. SmallPtrSet<SUnit *, 8> Visited;
  3073. SmallVector<SDep, 8> Worklist;
  3074. Worklist.push_back(Dep);
  3075. int EarlyCycle = INT_MAX;
  3076. while (!Worklist.empty()) {
  3077. const SDep &Cur = Worklist.pop_back_val();
  3078. SUnit *PrevSU = Cur.getSUnit();
  3079. if (Visited.count(PrevSU))
  3080. continue;
  3081. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
  3082. if (it == InstrToCycle.end())
  3083. continue;
  3084. EarlyCycle = std::min(EarlyCycle, it->second);
  3085. for (const auto &PI : PrevSU->Preds)
  3086. if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  3087. Worklist.push_back(PI);
  3088. Visited.insert(PrevSU);
  3089. }
  3090. return EarlyCycle;
  3091. }
  3092. // Return the cycle of the latest scheduled instruction in the chain.
  3093. int SMSchedule::latestCycleInChain(const SDep &Dep) {
  3094. SmallPtrSet<SUnit *, 8> Visited;
  3095. SmallVector<SDep, 8> Worklist;
  3096. Worklist.push_back(Dep);
  3097. int LateCycle = INT_MIN;
  3098. while (!Worklist.empty()) {
  3099. const SDep &Cur = Worklist.pop_back_val();
  3100. SUnit *SuccSU = Cur.getSUnit();
  3101. if (Visited.count(SuccSU))
  3102. continue;
  3103. std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
  3104. if (it == InstrToCycle.end())
  3105. continue;
  3106. LateCycle = std::max(LateCycle, it->second);
  3107. for (const auto &SI : SuccSU->Succs)
  3108. if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
  3109. Worklist.push_back(SI);
  3110. Visited.insert(SuccSU);
  3111. }
  3112. return LateCycle;
  3113. }
  3114. /// If an instruction has a use that spans multiple iterations, then
  3115. /// return true. These instructions are characterized by having a back-ege
  3116. /// to a Phi, which contains a reference to another Phi.
  3117. static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
  3118. for (auto &P : SU->Preds)
  3119. if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
  3120. for (auto &S : P.getSUnit()->Succs)
  3121. if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
  3122. return P.getSUnit();
  3123. return nullptr;
  3124. }
  3125. /// Compute the scheduling start slot for the instruction. The start slot
  3126. /// depends on any predecessor or successor nodes scheduled already.
  3127. void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
  3128. int *MinEnd, int *MaxStart, int II,
  3129. SwingSchedulerDAG *DAG) {
  3130. // Iterate over each instruction that has been scheduled already. The start
  3131. // slot computation depends on whether the previously scheduled instruction
  3132. // is a predecessor or successor of the specified instruction.
  3133. for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
  3134. // Iterate over each instruction in the current cycle.
  3135. for (SUnit *I : getInstructions(cycle)) {
  3136. // Because we're processing a DAG for the dependences, we recognize
  3137. // the back-edge in recurrences by anti dependences.
  3138. for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
  3139. const SDep &Dep = SU->Preds[i];
  3140. if (Dep.getSUnit() == I) {
  3141. if (!DAG->isBackedge(SU, Dep)) {
  3142. int EarlyStart = cycle + Dep.getLatency() -
  3143. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  3144. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  3145. if (DAG->isLoopCarriedDep(SU, Dep, false)) {
  3146. int End = earliestCycleInChain(Dep) + (II - 1);
  3147. *MinEnd = std::min(*MinEnd, End);
  3148. }
  3149. } else {
  3150. int LateStart = cycle - Dep.getLatency() +
  3151. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  3152. *MinLateStart = std::min(*MinLateStart, LateStart);
  3153. }
  3154. }
  3155. // For instruction that requires multiple iterations, make sure that
  3156. // the dependent instruction is not scheduled past the definition.
  3157. SUnit *BE = multipleIterations(I, DAG);
  3158. if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
  3159. !SU->isPred(I))
  3160. *MinLateStart = std::min(*MinLateStart, cycle);
  3161. }
  3162. for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
  3163. if (SU->Succs[i].getSUnit() == I) {
  3164. const SDep &Dep = SU->Succs[i];
  3165. if (!DAG->isBackedge(SU, Dep)) {
  3166. int LateStart = cycle - Dep.getLatency() +
  3167. DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
  3168. *MinLateStart = std::min(*MinLateStart, LateStart);
  3169. if (DAG->isLoopCarriedDep(SU, Dep)) {
  3170. int Start = latestCycleInChain(Dep) + 1 - II;
  3171. *MaxStart = std::max(*MaxStart, Start);
  3172. }
  3173. } else {
  3174. int EarlyStart = cycle + Dep.getLatency() -
  3175. DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
  3176. *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
  3177. }
  3178. }
  3179. }
  3180. }
  3181. }
  3182. }
  3183. /// Order the instructions within a cycle so that the definitions occur
  3184. /// before the uses. Returns true if the instruction is added to the start
  3185. /// of the list, or false if added to the end.
  3186. void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
  3187. std::deque<SUnit *> &Insts) {
  3188. MachineInstr *MI = SU->getInstr();
  3189. bool OrderBeforeUse = false;
  3190. bool OrderAfterDef = false;
  3191. bool OrderBeforeDef = false;
  3192. unsigned MoveDef = 0;
  3193. unsigned MoveUse = 0;
  3194. int StageInst1 = stageScheduled(SU);
  3195. unsigned Pos = 0;
  3196. for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
  3197. ++I, ++Pos) {
  3198. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3199. MachineOperand &MO = MI->getOperand(i);
  3200. if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  3201. continue;
  3202. unsigned Reg = MO.getReg();
  3203. unsigned BasePos, OffsetPos;
  3204. if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
  3205. if (MI->getOperand(BasePos).getReg() == Reg)
  3206. if (unsigned NewReg = SSD->getInstrBaseReg(SU))
  3207. Reg = NewReg;
  3208. bool Reads, Writes;
  3209. std::tie(Reads, Writes) =
  3210. (*I)->getInstr()->readsWritesVirtualRegister(Reg);
  3211. if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
  3212. OrderBeforeUse = true;
  3213. if (MoveUse == 0)
  3214. MoveUse = Pos;
  3215. } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
  3216. // Add the instruction after the scheduled instruction.
  3217. OrderAfterDef = true;
  3218. MoveDef = Pos;
  3219. } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
  3220. if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
  3221. OrderBeforeUse = true;
  3222. if (MoveUse == 0)
  3223. MoveUse = Pos;
  3224. } else {
  3225. OrderAfterDef = true;
  3226. MoveDef = Pos;
  3227. }
  3228. } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
  3229. OrderBeforeUse = true;
  3230. if (MoveUse == 0)
  3231. MoveUse = Pos;
  3232. if (MoveUse != 0) {
  3233. OrderAfterDef = true;
  3234. MoveDef = Pos - 1;
  3235. }
  3236. } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
  3237. // Add the instruction before the scheduled instruction.
  3238. OrderBeforeUse = true;
  3239. if (MoveUse == 0)
  3240. MoveUse = Pos;
  3241. } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
  3242. isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
  3243. if (MoveUse == 0) {
  3244. OrderBeforeDef = true;
  3245. MoveUse = Pos;
  3246. }
  3247. }
  3248. }
  3249. // Check for order dependences between instructions. Make sure the source
  3250. // is ordered before the destination.
  3251. for (auto &S : SU->Succs) {
  3252. if (S.getSUnit() != *I)
  3253. continue;
  3254. if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  3255. OrderBeforeUse = true;
  3256. if (Pos < MoveUse)
  3257. MoveUse = Pos;
  3258. }
  3259. }
  3260. for (auto &P : SU->Preds) {
  3261. if (P.getSUnit() != *I)
  3262. continue;
  3263. if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
  3264. OrderAfterDef = true;
  3265. MoveDef = Pos;
  3266. }
  3267. }
  3268. }
  3269. // A circular dependence.
  3270. if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
  3271. OrderBeforeUse = false;
  3272. // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
  3273. // to a loop-carried dependence.
  3274. if (OrderBeforeDef)
  3275. OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
  3276. // The uncommon case when the instruction order needs to be updated because
  3277. // there is both a use and def.
  3278. if (OrderBeforeUse && OrderAfterDef) {
  3279. SUnit *UseSU = Insts.at(MoveUse);
  3280. SUnit *DefSU = Insts.at(MoveDef);
  3281. if (MoveUse > MoveDef) {
  3282. Insts.erase(Insts.begin() + MoveUse);
  3283. Insts.erase(Insts.begin() + MoveDef);
  3284. } else {
  3285. Insts.erase(Insts.begin() + MoveDef);
  3286. Insts.erase(Insts.begin() + MoveUse);
  3287. }
  3288. orderDependence(SSD, UseSU, Insts);
  3289. orderDependence(SSD, SU, Insts);
  3290. orderDependence(SSD, DefSU, Insts);
  3291. return;
  3292. }
  3293. // Put the new instruction first if there is a use in the list. Otherwise,
  3294. // put it at the end of the list.
  3295. if (OrderBeforeUse)
  3296. Insts.push_front(SU);
  3297. else
  3298. Insts.push_back(SU);
  3299. }
  3300. /// Return true if the scheduled Phi has a loop carried operand.
  3301. bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
  3302. if (!Phi.isPHI())
  3303. return false;
  3304. assert(Phi.isPHI() && "Expecting a Phi.");
  3305. SUnit *DefSU = SSD->getSUnit(&Phi);
  3306. unsigned DefCycle = cycleScheduled(DefSU);
  3307. int DefStage = stageScheduled(DefSU);
  3308. unsigned InitVal = 0;
  3309. unsigned LoopVal = 0;
  3310. getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
  3311. SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
  3312. if (!UseSU)
  3313. return true;
  3314. if (UseSU->getInstr()->isPHI())
  3315. return true;
  3316. unsigned LoopCycle = cycleScheduled(UseSU);
  3317. int LoopStage = stageScheduled(UseSU);
  3318. return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
  3319. }
  3320. /// Return true if the instruction is a definition that is loop carried
  3321. /// and defines the use on the next iteration.
  3322. /// v1 = phi(v2, v3)
  3323. /// (Def) v3 = op v1
  3324. /// (MO) = v1
  3325. /// If MO appears before Def, then then v1 and v3 may get assigned to the same
  3326. /// register.
  3327. bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
  3328. MachineInstr *Def, MachineOperand &MO) {
  3329. if (!MO.isReg())
  3330. return false;
  3331. if (Def->isPHI())
  3332. return false;
  3333. MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
  3334. if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
  3335. return false;
  3336. if (!isLoopCarried(SSD, *Phi))
  3337. return false;
  3338. unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
  3339. for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
  3340. MachineOperand &DMO = Def->getOperand(i);
  3341. if (!DMO.isReg() || !DMO.isDef())
  3342. continue;
  3343. if (DMO.getReg() == LoopReg)
  3344. return true;
  3345. }
  3346. return false;
  3347. }
  3348. // Check if the generated schedule is valid. This function checks if
  3349. // an instruction that uses a physical register is scheduled in a
  3350. // different stage than the definition. The pipeliner does not handle
  3351. // physical register values that may cross a basic block boundary.
  3352. bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
  3353. for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
  3354. SUnit &SU = SSD->SUnits[i];
  3355. if (!SU.hasPhysRegDefs)
  3356. continue;
  3357. int StageDef = stageScheduled(&SU);
  3358. assert(StageDef != -1 && "Instruction should have been scheduled.");
  3359. for (auto &SI : SU.Succs)
  3360. if (SI.isAssignedRegDep())
  3361. if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
  3362. if (stageScheduled(SI.getSUnit()) != StageDef)
  3363. return false;
  3364. }
  3365. return true;
  3366. }
  3367. /// A property of the node order in swing-modulo-scheduling is
  3368. /// that for nodes outside circuits the following holds:
  3369. /// none of them is scheduled after both a successor and a
  3370. /// predecessor.
  3371. /// The method below checks whether the property is met.
  3372. /// If not, debug information is printed and statistics information updated.
  3373. /// Note that we do not use an assert statement.
  3374. /// The reason is that although an invalid node oder may prevent
  3375. /// the pipeliner from finding a pipelined schedule for arbitrary II,
  3376. /// it does not lead to the generation of incorrect code.
  3377. void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
  3378. // a sorted vector that maps each SUnit to its index in the NodeOrder
  3379. typedef std::pair<SUnit *, unsigned> UnitIndex;
  3380. std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
  3381. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
  3382. Indices.push_back(std::make_pair(NodeOrder[i], i));
  3383. auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
  3384. return std::get<0>(i1) < std::get<0>(i2);
  3385. };
  3386. // sort, so that we can perform a binary search
  3387. llvm::sort(Indices, CompareKey);
  3388. bool Valid = true;
  3389. (void)Valid;
  3390. // for each SUnit in the NodeOrder, check whether
  3391. // it appears after both a successor and a predecessor
  3392. // of the SUnit. If this is the case, and the SUnit
  3393. // is not part of circuit, then the NodeOrder is not
  3394. // valid.
  3395. for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
  3396. SUnit *SU = NodeOrder[i];
  3397. unsigned Index = i;
  3398. bool PredBefore = false;
  3399. bool SuccBefore = false;
  3400. SUnit *Succ;
  3401. SUnit *Pred;
  3402. (void)Succ;
  3403. (void)Pred;
  3404. for (SDep &PredEdge : SU->Preds) {
  3405. SUnit *PredSU = PredEdge.getSUnit();
  3406. unsigned PredIndex =
  3407. std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
  3408. std::make_pair(PredSU, 0), CompareKey));
  3409. if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
  3410. PredBefore = true;
  3411. Pred = PredSU;
  3412. break;
  3413. }
  3414. }
  3415. for (SDep &SuccEdge : SU->Succs) {
  3416. SUnit *SuccSU = SuccEdge.getSUnit();
  3417. // Do not process a boundary node, it was not included in NodeOrder,
  3418. // hence not in Indices either, call to std::lower_bound() below will
  3419. // return Indices.end().
  3420. if (SuccSU->isBoundaryNode())
  3421. continue;
  3422. unsigned SuccIndex =
  3423. std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(),
  3424. std::make_pair(SuccSU, 0), CompareKey));
  3425. if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
  3426. SuccBefore = true;
  3427. Succ = SuccSU;
  3428. break;
  3429. }
  3430. }
  3431. if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
  3432. // instructions in circuits are allowed to be scheduled
  3433. // after both a successor and predecessor.
  3434. bool InCircuit = std::any_of(
  3435. Circuits.begin(), Circuits.end(),
  3436. [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
  3437. if (InCircuit)
  3438. LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
  3439. else {
  3440. Valid = false;
  3441. NumNodeOrderIssues++;
  3442. LLVM_DEBUG(dbgs() << "Predecessor ";);
  3443. }
  3444. LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
  3445. << " are scheduled before node " << SU->NodeNum
  3446. << "\n";);
  3447. }
  3448. }
  3449. LLVM_DEBUG({
  3450. if (!Valid)
  3451. dbgs() << "Invalid node order found!\n";
  3452. });
  3453. }
  3454. /// Attempt to fix the degenerate cases when the instruction serialization
  3455. /// causes the register lifetimes to overlap. For example,
  3456. /// p' = store_pi(p, b)
  3457. /// = load p, offset
  3458. /// In this case p and p' overlap, which means that two registers are needed.
  3459. /// Instead, this function changes the load to use p' and updates the offset.
  3460. void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
  3461. unsigned OverlapReg = 0;
  3462. unsigned NewBaseReg = 0;
  3463. for (SUnit *SU : Instrs) {
  3464. MachineInstr *MI = SU->getInstr();
  3465. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3466. const MachineOperand &MO = MI->getOperand(i);
  3467. // Look for an instruction that uses p. The instruction occurs in the
  3468. // same cycle but occurs later in the serialized order.
  3469. if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
  3470. // Check that the instruction appears in the InstrChanges structure,
  3471. // which contains instructions that can have the offset updated.
  3472. DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
  3473. InstrChanges.find(SU);
  3474. if (It != InstrChanges.end()) {
  3475. unsigned BasePos, OffsetPos;
  3476. // Update the base register and adjust the offset.
  3477. if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
  3478. MachineInstr *NewMI = MF.CloneMachineInstr(MI);
  3479. NewMI->getOperand(BasePos).setReg(NewBaseReg);
  3480. int64_t NewOffset =
  3481. MI->getOperand(OffsetPos).getImm() - It->second.second;
  3482. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  3483. SU->setInstr(NewMI);
  3484. MISUnitMap[NewMI] = SU;
  3485. NewMIs.insert(NewMI);
  3486. }
  3487. }
  3488. OverlapReg = 0;
  3489. NewBaseReg = 0;
  3490. break;
  3491. }
  3492. // Look for an instruction of the form p' = op(p), which uses and defines
  3493. // two virtual registers that get allocated to the same physical register.
  3494. unsigned TiedUseIdx = 0;
  3495. if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
  3496. // OverlapReg is p in the example above.
  3497. OverlapReg = MI->getOperand(TiedUseIdx).getReg();
  3498. // NewBaseReg is p' in the example above.
  3499. NewBaseReg = MI->getOperand(i).getReg();
  3500. break;
  3501. }
  3502. }
  3503. }
  3504. }
  3505. /// After the schedule has been formed, call this function to combine
  3506. /// the instructions from the different stages/cycles. That is, this
  3507. /// function creates a schedule that represents a single iteration.
  3508. void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
  3509. // Move all instructions to the first stage from later stages.
  3510. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  3511. for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
  3512. ++stage) {
  3513. std::deque<SUnit *> &cycleInstrs =
  3514. ScheduledInstrs[cycle + (stage * InitiationInterval)];
  3515. for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
  3516. E = cycleInstrs.rend();
  3517. I != E; ++I)
  3518. ScheduledInstrs[cycle].push_front(*I);
  3519. }
  3520. }
  3521. // Iterate over the definitions in each instruction, and compute the
  3522. // stage difference for each use. Keep the maximum value.
  3523. for (auto &I : InstrToCycle) {
  3524. int DefStage = stageScheduled(I.first);
  3525. MachineInstr *MI = I.first->getInstr();
  3526. for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
  3527. MachineOperand &Op = MI->getOperand(i);
  3528. if (!Op.isReg() || !Op.isDef())
  3529. continue;
  3530. unsigned Reg = Op.getReg();
  3531. unsigned MaxDiff = 0;
  3532. bool PhiIsSwapped = false;
  3533. for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
  3534. EI = MRI.use_end();
  3535. UI != EI; ++UI) {
  3536. MachineOperand &UseOp = *UI;
  3537. MachineInstr *UseMI = UseOp.getParent();
  3538. SUnit *SUnitUse = SSD->getSUnit(UseMI);
  3539. int UseStage = stageScheduled(SUnitUse);
  3540. unsigned Diff = 0;
  3541. if (UseStage != -1 && UseStage >= DefStage)
  3542. Diff = UseStage - DefStage;
  3543. if (MI->isPHI()) {
  3544. if (isLoopCarried(SSD, *MI))
  3545. ++Diff;
  3546. else
  3547. PhiIsSwapped = true;
  3548. }
  3549. MaxDiff = std::max(Diff, MaxDiff);
  3550. }
  3551. RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
  3552. }
  3553. }
  3554. // Erase all the elements in the later stages. Only one iteration should
  3555. // remain in the scheduled list, and it contains all the instructions.
  3556. for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
  3557. ScheduledInstrs.erase(cycle);
  3558. // Change the registers in instruction as specified in the InstrChanges
  3559. // map. We need to use the new registers to create the correct order.
  3560. for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
  3561. SUnit *SU = &SSD->SUnits[i];
  3562. SSD->applyInstrChange(SU->getInstr(), *this);
  3563. }
  3564. // Reorder the instructions in each cycle to fix and improve the
  3565. // generated code.
  3566. for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
  3567. std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
  3568. std::deque<SUnit *> newOrderPhi;
  3569. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  3570. SUnit *SU = cycleInstrs[i];
  3571. if (SU->getInstr()->isPHI())
  3572. newOrderPhi.push_back(SU);
  3573. }
  3574. std::deque<SUnit *> newOrderI;
  3575. for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
  3576. SUnit *SU = cycleInstrs[i];
  3577. if (!SU->getInstr()->isPHI())
  3578. orderDependence(SSD, SU, newOrderI);
  3579. }
  3580. // Replace the old order with the new order.
  3581. cycleInstrs.swap(newOrderPhi);
  3582. cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
  3583. SSD->fixupRegisterOverlaps(cycleInstrs);
  3584. }
  3585. LLVM_DEBUG(dump(););
  3586. }
  3587. void NodeSet::print(raw_ostream &os) const {
  3588. os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
  3589. << " depth " << MaxDepth << " col " << Colocate << "\n";
  3590. for (const auto &I : Nodes)
  3591. os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
  3592. os << "\n";
  3593. }
  3594. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  3595. /// Print the schedule information to the given output.
  3596. void SMSchedule::print(raw_ostream &os) const {
  3597. // Iterate over each cycle.
  3598. for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
  3599. // Iterate over each instruction in the cycle.
  3600. const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
  3601. for (SUnit *CI : cycleInstrs->second) {
  3602. os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
  3603. os << "(" << CI->NodeNum << ") ";
  3604. CI->getInstr()->print(os);
  3605. os << "\n";
  3606. }
  3607. }
  3608. }
  3609. /// Utility function used for debugging to print the schedule.
  3610. LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
  3611. LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
  3612. #endif
  3613. void ResourceManager::initProcResourceVectors(
  3614. const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
  3615. unsigned ProcResourceID = 0;
  3616. // We currently limit the resource kinds to 64 and below so that we can use
  3617. // uint64_t for Masks
  3618. assert(SM.getNumProcResourceKinds() < 64 &&
  3619. "Too many kinds of resources, unsupported");
  3620. // Create a unique bitmask for every processor resource unit.
  3621. // Skip resource at index 0, since it always references 'InvalidUnit'.
  3622. Masks.resize(SM.getNumProcResourceKinds());
  3623. for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
  3624. const MCProcResourceDesc &Desc = *SM.getProcResource(I);
  3625. if (Desc.SubUnitsIdxBegin)
  3626. continue;
  3627. Masks[I] = 1ULL << ProcResourceID;
  3628. ProcResourceID++;
  3629. }
  3630. // Create a unique bitmask for every processor resource group.
  3631. for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
  3632. const MCProcResourceDesc &Desc = *SM.getProcResource(I);
  3633. if (!Desc.SubUnitsIdxBegin)
  3634. continue;
  3635. Masks[I] = 1ULL << ProcResourceID;
  3636. for (unsigned U = 0; U < Desc.NumUnits; ++U)
  3637. Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
  3638. ProcResourceID++;
  3639. }
  3640. LLVM_DEBUG({
  3641. if (SwpShowResMask) {
  3642. dbgs() << "ProcResourceDesc:\n";
  3643. for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
  3644. const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
  3645. dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
  3646. ProcResource->Name, I, Masks[I],
  3647. ProcResource->NumUnits);
  3648. }
  3649. dbgs() << " -----------------\n";
  3650. }
  3651. });
  3652. }
  3653. bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
  3654. LLVM_DEBUG({
  3655. if (SwpDebugResource)
  3656. dbgs() << "canReserveResources:\n";
  3657. });
  3658. if (UseDFA)
  3659. return DFAResources->canReserveResources(MID);
  3660. unsigned InsnClass = MID->getSchedClass();
  3661. const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
  3662. if (!SCDesc->isValid()) {
  3663. LLVM_DEBUG({
  3664. dbgs() << "No valid Schedule Class Desc for schedClass!\n";
  3665. dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
  3666. });
  3667. return true;
  3668. }
  3669. const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
  3670. const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
  3671. for (; I != E; ++I) {
  3672. if (!I->Cycles)
  3673. continue;
  3674. const MCProcResourceDesc *ProcResource =
  3675. SM.getProcResource(I->ProcResourceIdx);
  3676. unsigned NumUnits = ProcResource->NumUnits;
  3677. LLVM_DEBUG({
  3678. if (SwpDebugResource)
  3679. dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
  3680. ProcResource->Name, I->ProcResourceIdx,
  3681. ProcResourceCount[I->ProcResourceIdx], NumUnits,
  3682. I->Cycles);
  3683. });
  3684. if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
  3685. return false;
  3686. }
  3687. LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
  3688. return true;
  3689. }
  3690. void ResourceManager::reserveResources(const MCInstrDesc *MID) {
  3691. LLVM_DEBUG({
  3692. if (SwpDebugResource)
  3693. dbgs() << "reserveResources:\n";
  3694. });
  3695. if (UseDFA)
  3696. return DFAResources->reserveResources(MID);
  3697. unsigned InsnClass = MID->getSchedClass();
  3698. const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
  3699. if (!SCDesc->isValid()) {
  3700. LLVM_DEBUG({
  3701. dbgs() << "No valid Schedule Class Desc for schedClass!\n";
  3702. dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
  3703. });
  3704. return;
  3705. }
  3706. for (const MCWriteProcResEntry &PRE :
  3707. make_range(STI->getWriteProcResBegin(SCDesc),
  3708. STI->getWriteProcResEnd(SCDesc))) {
  3709. if (!PRE.Cycles)
  3710. continue;
  3711. ++ProcResourceCount[PRE.ProcResourceIdx];
  3712. LLVM_DEBUG({
  3713. if (SwpDebugResource) {
  3714. const MCProcResourceDesc *ProcResource =
  3715. SM.getProcResource(PRE.ProcResourceIdx);
  3716. dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
  3717. ProcResource->Name, PRE.ProcResourceIdx,
  3718. ProcResourceCount[PRE.ProcResourceIdx],
  3719. ProcResource->NumUnits, PRE.Cycles);
  3720. }
  3721. });
  3722. }
  3723. LLVM_DEBUG({
  3724. if (SwpDebugResource)
  3725. dbgs() << "reserveResources: done!\n\n";
  3726. });
  3727. }
  3728. bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
  3729. return canReserveResources(&MI.getDesc());
  3730. }
  3731. void ResourceManager::reserveResources(const MachineInstr &MI) {
  3732. return reserveResources(&MI.getDesc());
  3733. }
  3734. void ResourceManager::clearResources() {
  3735. if (UseDFA)
  3736. return DFAResources->clearResources();
  3737. std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
  3738. }