MachinePipeliner.cpp 152 KB

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