MachinePipeliner.cpp 149 KB

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