MachinePipeliner.cpp 142 KB

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