ScheduleDAGInstrs.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  1. //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
  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. /// \file This implements the ScheduleDAGInstrs class, which implements
  10. /// re-scheduling of MachineInstrs.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  14. #include "llvm/ADT/IntEqClasses.h"
  15. #include "llvm/ADT/MapVector.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/SparseSet.h"
  19. #include "llvm/ADT/iterator_range.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/CodeGen/LiveIntervals.h"
  23. #include "llvm/CodeGen/LivePhysRegs.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineFrameInfo.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineInstr.h"
  28. #include "llvm/CodeGen/MachineInstrBundle.h"
  29. #include "llvm/CodeGen/MachineMemOperand.h"
  30. #include "llvm/CodeGen/MachineOperand.h"
  31. #include "llvm/CodeGen/MachineRegisterInfo.h"
  32. #include "llvm/CodeGen/PseudoSourceValue.h"
  33. #include "llvm/CodeGen/RegisterPressure.h"
  34. #include "llvm/CodeGen/ScheduleDAG.h"
  35. #include "llvm/CodeGen/ScheduleDFS.h"
  36. #include "llvm/CodeGen/SlotIndexes.h"
  37. #include "llvm/CodeGen/TargetRegisterInfo.h"
  38. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  39. #include "llvm/Config/llvm-config.h"
  40. #include "llvm/IR/Constants.h"
  41. #include "llvm/IR/Function.h"
  42. #include "llvm/IR/Instruction.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/Operator.h"
  45. #include "llvm/IR/Type.h"
  46. #include "llvm/IR/Value.h"
  47. #include "llvm/MC/LaneBitmask.h"
  48. #include "llvm/MC/MCRegisterInfo.h"
  49. #include "llvm/Support/Casting.h"
  50. #include "llvm/Support/CommandLine.h"
  51. #include "llvm/Support/Compiler.h"
  52. #include "llvm/Support/Debug.h"
  53. #include "llvm/Support/ErrorHandling.h"
  54. #include "llvm/Support/Format.h"
  55. #include "llvm/Support/raw_ostream.h"
  56. #include <algorithm>
  57. #include <cassert>
  58. #include <iterator>
  59. #include <string>
  60. #include <utility>
  61. #include <vector>
  62. using namespace llvm;
  63. #define DEBUG_TYPE "machine-scheduler"
  64. static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
  65. cl::ZeroOrMore, cl::init(false),
  66. cl::desc("Enable use of AA during MI DAG construction"));
  67. static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
  68. cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
  69. // Note: the two options below might be used in tuning compile time vs
  70. // output quality. Setting HugeRegion so large that it will never be
  71. // reached means best-effort, but may be slow.
  72. // When Stores and Loads maps (or NonAliasStores and NonAliasLoads)
  73. // together hold this many SUs, a reduction of maps will be done.
  74. static cl::opt<unsigned> HugeRegion("dag-maps-huge-region", cl::Hidden,
  75. cl::init(1000), cl::desc("The limit to use while constructing the DAG "
  76. "prior to scheduling, at which point a trade-off "
  77. "is made to avoid excessive compile time."));
  78. static cl::opt<unsigned> ReductionSize(
  79. "dag-maps-reduction-size", cl::Hidden,
  80. cl::desc("A huge scheduling region will have maps reduced by this many "
  81. "nodes at a time. Defaults to HugeRegion / 2."));
  82. static unsigned getReductionSize() {
  83. // Always reduce a huge region with half of the elements, except
  84. // when user sets this number explicitly.
  85. if (ReductionSize.getNumOccurrences() == 0)
  86. return HugeRegion / 2;
  87. return ReductionSize;
  88. }
  89. static void dumpSUList(ScheduleDAGInstrs::SUList &L) {
  90. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  91. dbgs() << "{ ";
  92. for (const SUnit *su : L) {
  93. dbgs() << "SU(" << su->NodeNum << ")";
  94. if (su != L.back())
  95. dbgs() << ", ";
  96. }
  97. dbgs() << "}\n";
  98. #endif
  99. }
  100. ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
  101. const MachineLoopInfo *mli,
  102. bool RemoveKillFlags)
  103. : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
  104. RemoveKillFlags(RemoveKillFlags),
  105. UnknownValue(UndefValue::get(
  106. Type::getVoidTy(mf.getFunction().getContext()))), Topo(SUnits, &ExitSU) {
  107. DbgValues.clear();
  108. const TargetSubtargetInfo &ST = mf.getSubtarget();
  109. SchedModel.init(&ST);
  110. }
  111. /// If this machine instr has memory reference information and it can be
  112. /// tracked to a normal reference to a known object, return the Value
  113. /// for that object. This function returns false the memory location is
  114. /// unknown or may alias anything.
  115. static bool getUnderlyingObjectsForInstr(const MachineInstr *MI,
  116. const MachineFrameInfo &MFI,
  117. UnderlyingObjectsVector &Objects,
  118. const DataLayout &DL) {
  119. auto allMMOsOkay = [&]() {
  120. for (const MachineMemOperand *MMO : MI->memoperands()) {
  121. // TODO: Figure out whether isAtomic is really necessary (see D57601).
  122. if (MMO->isVolatile() || MMO->isAtomic())
  123. return false;
  124. if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
  125. // Function that contain tail calls don't have unique PseudoSourceValue
  126. // objects. Two PseudoSourceValues might refer to the same or
  127. // overlapping locations. The client code calling this function assumes
  128. // this is not the case. So return a conservative answer of no known
  129. // object.
  130. if (MFI.hasTailCall())
  131. return false;
  132. // For now, ignore PseudoSourceValues which may alias LLVM IR values
  133. // because the code that uses this function has no way to cope with
  134. // such aliases.
  135. if (PSV->isAliased(&MFI))
  136. return false;
  137. bool MayAlias = PSV->mayAlias(&MFI);
  138. Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
  139. } else if (const Value *V = MMO->getValue()) {
  140. SmallVector<Value *, 4> Objs;
  141. if (!getUnderlyingObjectsForCodeGen(V, Objs))
  142. return false;
  143. for (Value *V : Objs) {
  144. assert(isIdentifiedObject(V));
  145. Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
  146. }
  147. } else
  148. return false;
  149. }
  150. return true;
  151. };
  152. if (!allMMOsOkay()) {
  153. Objects.clear();
  154. return false;
  155. }
  156. return true;
  157. }
  158. void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
  159. BB = bb;
  160. }
  161. void ScheduleDAGInstrs::finishBlock() {
  162. // Subclasses should no longer refer to the old block.
  163. BB = nullptr;
  164. }
  165. void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
  166. MachineBasicBlock::iterator begin,
  167. MachineBasicBlock::iterator end,
  168. unsigned regioninstrs) {
  169. assert(bb == BB && "startBlock should set BB");
  170. RegionBegin = begin;
  171. RegionEnd = end;
  172. NumRegionInstrs = regioninstrs;
  173. }
  174. void ScheduleDAGInstrs::exitRegion() {
  175. // Nothing to do.
  176. }
  177. void ScheduleDAGInstrs::addSchedBarrierDeps() {
  178. MachineInstr *ExitMI =
  179. RegionEnd != BB->end()
  180. ? &*skipDebugInstructionsBackward(RegionEnd, RegionBegin)
  181. : nullptr;
  182. ExitSU.setInstr(ExitMI);
  183. // Add dependencies on the defs and uses of the instruction.
  184. if (ExitMI) {
  185. for (const MachineOperand &MO : ExitMI->operands()) {
  186. if (!MO.isReg() || MO.isDef()) continue;
  187. Register Reg = MO.getReg();
  188. if (Register::isPhysicalRegister(Reg)) {
  189. Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
  190. } else if (Register::isVirtualRegister(Reg) && MO.readsReg()) {
  191. addVRegUseDeps(&ExitSU, ExitMI->getOperandNo(&MO));
  192. }
  193. }
  194. }
  195. if (!ExitMI || (!ExitMI->isCall() && !ExitMI->isBarrier())) {
  196. // For others, e.g. fallthrough, conditional branch, assume the exit
  197. // uses all the registers that are livein to the successor blocks.
  198. for (const MachineBasicBlock *Succ : BB->successors()) {
  199. for (const auto &LI : Succ->liveins()) {
  200. if (!Uses.contains(LI.PhysReg))
  201. Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
  202. }
  203. }
  204. }
  205. }
  206. /// MO is an operand of SU's instruction that defines a physical register. Adds
  207. /// data dependencies from SU to any uses of the physical register.
  208. void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
  209. const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
  210. assert(MO.isDef() && "expect physreg def");
  211. // Ask the target if address-backscheduling is desirable, and if so how much.
  212. const TargetSubtargetInfo &ST = MF.getSubtarget();
  213. // Only use any non-zero latency for real defs/uses, in contrast to
  214. // "fake" operands added by regalloc.
  215. const MCInstrDesc *DefMIDesc = &SU->getInstr()->getDesc();
  216. bool ImplicitPseudoDef = (OperIdx >= DefMIDesc->getNumOperands() &&
  217. !DefMIDesc->hasImplicitDefOfPhysReg(MO.getReg()));
  218. for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
  219. Alias.isValid(); ++Alias) {
  220. for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
  221. SUnit *UseSU = I->SU;
  222. if (UseSU == SU)
  223. continue;
  224. // Adjust the dependence latency using operand def/use information,
  225. // then allow the target to perform its own adjustments.
  226. int UseOp = I->OpIdx;
  227. MachineInstr *RegUse = nullptr;
  228. SDep Dep;
  229. if (UseOp < 0)
  230. Dep = SDep(SU, SDep::Artificial);
  231. else {
  232. // Set the hasPhysRegDefs only for physreg defs that have a use within
  233. // the scheduling region.
  234. SU->hasPhysRegDefs = true;
  235. Dep = SDep(SU, SDep::Data, *Alias);
  236. RegUse = UseSU->getInstr();
  237. }
  238. const MCInstrDesc *UseMIDesc =
  239. (RegUse ? &UseSU->getInstr()->getDesc() : nullptr);
  240. bool ImplicitPseudoUse =
  241. (UseMIDesc && UseOp >= ((int)UseMIDesc->getNumOperands()) &&
  242. !UseMIDesc->hasImplicitUseOfPhysReg(*Alias));
  243. if (!ImplicitPseudoDef && !ImplicitPseudoUse) {
  244. Dep.setLatency(SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
  245. RegUse, UseOp));
  246. ST.adjustSchedDependency(SU, OperIdx, UseSU, UseOp, Dep);
  247. } else {
  248. Dep.setLatency(0);
  249. // FIXME: We could always let target to adjustSchedDependency(), and
  250. // remove this condition, but that currently asserts in Hexagon BE.
  251. if (SU->getInstr()->isBundle() || (RegUse && RegUse->isBundle()))
  252. ST.adjustSchedDependency(SU, OperIdx, UseSU, UseOp, Dep);
  253. }
  254. UseSU->addPred(Dep);
  255. }
  256. }
  257. }
  258. /// Adds register dependencies (data, anti, and output) from this SUnit
  259. /// to following instructions in the same scheduling region that depend the
  260. /// physical register referenced at OperIdx.
  261. void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
  262. MachineInstr *MI = SU->getInstr();
  263. MachineOperand &MO = MI->getOperand(OperIdx);
  264. Register Reg = MO.getReg();
  265. // We do not need to track any dependencies for constant registers.
  266. if (MRI.isConstantPhysReg(Reg))
  267. return;
  268. const TargetSubtargetInfo &ST = MF.getSubtarget();
  269. // Optionally add output and anti dependencies. For anti
  270. // dependencies we use a latency of 0 because for a multi-issue
  271. // target we want to allow the defining instruction to issue
  272. // in the same cycle as the using instruction.
  273. // TODO: Using a latency of 1 here for output dependencies assumes
  274. // there's no cost for reusing registers.
  275. SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
  276. for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
  277. if (!Defs.contains(*Alias))
  278. continue;
  279. for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
  280. SUnit *DefSU = I->SU;
  281. if (DefSU == &ExitSU)
  282. continue;
  283. if (DefSU != SU &&
  284. (Kind != SDep::Output || !MO.isDead() ||
  285. !DefSU->getInstr()->registerDefIsDead(*Alias))) {
  286. SDep Dep(SU, Kind, /*Reg=*/*Alias);
  287. if (Kind != SDep::Anti)
  288. Dep.setLatency(
  289. SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
  290. ST.adjustSchedDependency(SU, OperIdx, DefSU, I->OpIdx, Dep);
  291. DefSU->addPred(Dep);
  292. }
  293. }
  294. }
  295. if (!MO.isDef()) {
  296. SU->hasPhysRegUses = true;
  297. // Either insert a new Reg2SUnits entry with an empty SUnits list, or
  298. // retrieve the existing SUnits list for this register's uses.
  299. // Push this SUnit on the use list.
  300. Uses.insert(PhysRegSUOper(SU, OperIdx, Reg));
  301. if (RemoveKillFlags)
  302. MO.setIsKill(false);
  303. } else {
  304. addPhysRegDataDeps(SU, OperIdx);
  305. // Clear previous uses and defs of this register and its subergisters.
  306. for (MCSubRegIterator SubReg(Reg, TRI, true); SubReg.isValid(); ++SubReg) {
  307. if (Uses.contains(*SubReg))
  308. Uses.eraseAll(*SubReg);
  309. if (!MO.isDead())
  310. Defs.eraseAll(*SubReg);
  311. }
  312. if (MO.isDead() && SU->isCall) {
  313. // Calls will not be reordered because of chain dependencies (see
  314. // below). Since call operands are dead, calls may continue to be added
  315. // to the DefList making dependence checking quadratic in the size of
  316. // the block. Instead, we leave only one call at the back of the
  317. // DefList.
  318. Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
  319. Reg2SUnitsMap::iterator B = P.first;
  320. Reg2SUnitsMap::iterator I = P.second;
  321. for (bool isBegin = I == B; !isBegin; /* empty */) {
  322. isBegin = (--I) == B;
  323. if (!I->SU->isCall)
  324. break;
  325. I = Defs.erase(I);
  326. }
  327. }
  328. // Defs are pushed in the order they are visited and never reordered.
  329. Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
  330. }
  331. }
  332. LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
  333. {
  334. Register Reg = MO.getReg();
  335. // No point in tracking lanemasks if we don't have interesting subregisters.
  336. const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
  337. if (!RC.HasDisjunctSubRegs)
  338. return LaneBitmask::getAll();
  339. unsigned SubReg = MO.getSubReg();
  340. if (SubReg == 0)
  341. return RC.getLaneMask();
  342. return TRI->getSubRegIndexLaneMask(SubReg);
  343. }
  344. bool ScheduleDAGInstrs::deadDefHasNoUse(const MachineOperand &MO) {
  345. auto RegUse = CurrentVRegUses.find(MO.getReg());
  346. if (RegUse == CurrentVRegUses.end())
  347. return true;
  348. return (RegUse->LaneMask & getLaneMaskForMO(MO)).none();
  349. }
  350. /// Adds register output and data dependencies from this SUnit to instructions
  351. /// that occur later in the same scheduling region if they read from or write to
  352. /// the virtual register defined at OperIdx.
  353. ///
  354. /// TODO: Hoist loop induction variable increments. This has to be
  355. /// reevaluated. Generally, IV scheduling should be done before coalescing.
  356. void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
  357. MachineInstr *MI = SU->getInstr();
  358. MachineOperand &MO = MI->getOperand(OperIdx);
  359. Register Reg = MO.getReg();
  360. LaneBitmask DefLaneMask;
  361. LaneBitmask KillLaneMask;
  362. if (TrackLaneMasks) {
  363. bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
  364. DefLaneMask = getLaneMaskForMO(MO);
  365. // If we have a <read-undef> flag, none of the lane values comes from an
  366. // earlier instruction.
  367. KillLaneMask = IsKill ? LaneBitmask::getAll() : DefLaneMask;
  368. if (MO.getSubReg() != 0 && MO.isUndef()) {
  369. // There may be other subregister defs on the same instruction of the same
  370. // register in later operands. The lanes of other defs will now be live
  371. // after this instruction, so these should not be treated as killed by the
  372. // instruction even though they appear to be killed in this one operand.
  373. for (int I = OperIdx + 1, E = MI->getNumOperands(); I != E; ++I) {
  374. const MachineOperand &OtherMO = MI->getOperand(I);
  375. if (OtherMO.isReg() && OtherMO.isDef() && OtherMO.getReg() == Reg)
  376. KillLaneMask &= ~getLaneMaskForMO(OtherMO);
  377. }
  378. }
  379. // Clear undef flag, we'll re-add it later once we know which subregister
  380. // Def is first.
  381. MO.setIsUndef(false);
  382. } else {
  383. DefLaneMask = LaneBitmask::getAll();
  384. KillLaneMask = LaneBitmask::getAll();
  385. }
  386. if (MO.isDead()) {
  387. assert(deadDefHasNoUse(MO) && "Dead defs should have no uses");
  388. } else {
  389. // Add data dependence to all uses we found so far.
  390. const TargetSubtargetInfo &ST = MF.getSubtarget();
  391. for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
  392. E = CurrentVRegUses.end(); I != E; /*empty*/) {
  393. LaneBitmask LaneMask = I->LaneMask;
  394. // Ignore uses of other lanes.
  395. if ((LaneMask & KillLaneMask).none()) {
  396. ++I;
  397. continue;
  398. }
  399. if ((LaneMask & DefLaneMask).any()) {
  400. SUnit *UseSU = I->SU;
  401. MachineInstr *Use = UseSU->getInstr();
  402. SDep Dep(SU, SDep::Data, Reg);
  403. Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
  404. I->OperandIndex));
  405. ST.adjustSchedDependency(SU, OperIdx, UseSU, I->OperandIndex, Dep);
  406. UseSU->addPred(Dep);
  407. }
  408. LaneMask &= ~KillLaneMask;
  409. // If we found a Def for all lanes of this use, remove it from the list.
  410. if (LaneMask.any()) {
  411. I->LaneMask = LaneMask;
  412. ++I;
  413. } else
  414. I = CurrentVRegUses.erase(I);
  415. }
  416. }
  417. // Shortcut: Singly defined vregs do not have output/anti dependencies.
  418. if (MRI.hasOneDef(Reg))
  419. return;
  420. // Add output dependence to the next nearest defs of this vreg.
  421. //
  422. // Unless this definition is dead, the output dependence should be
  423. // transitively redundant with antidependencies from this definition's
  424. // uses. We're conservative for now until we have a way to guarantee the uses
  425. // are not eliminated sometime during scheduling. The output dependence edge
  426. // is also useful if output latency exceeds def-use latency.
  427. LaneBitmask LaneMask = DefLaneMask;
  428. for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
  429. CurrentVRegDefs.end())) {
  430. // Ignore defs for other lanes.
  431. if ((V2SU.LaneMask & LaneMask).none())
  432. continue;
  433. // Add an output dependence.
  434. SUnit *DefSU = V2SU.SU;
  435. // Ignore additional defs of the same lanes in one instruction. This can
  436. // happen because lanemasks are shared for targets with too many
  437. // subregisters. We also use some representration tricks/hacks where we
  438. // add super-register defs/uses, to imply that although we only access parts
  439. // of the reg we care about the full one.
  440. if (DefSU == SU)
  441. continue;
  442. SDep Dep(SU, SDep::Output, Reg);
  443. Dep.setLatency(
  444. SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
  445. DefSU->addPred(Dep);
  446. // Update current definition. This can get tricky if the def was about a
  447. // bigger lanemask before. We then have to shrink it and create a new
  448. // VReg2SUnit for the non-overlapping part.
  449. LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
  450. LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
  451. V2SU.SU = SU;
  452. V2SU.LaneMask = OverlapMask;
  453. if (NonOverlapMask.any())
  454. CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
  455. }
  456. // If there was no CurrentVRegDefs entry for some lanes yet, create one.
  457. if (LaneMask.any())
  458. CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
  459. }
  460. /// Adds a register data dependency if the instruction that defines the
  461. /// virtual register used at OperIdx is mapped to an SUnit. Add a register
  462. /// antidependency from this SUnit to instructions that occur later in the same
  463. /// scheduling region if they write the virtual register.
  464. ///
  465. /// TODO: Handle ExitSU "uses" properly.
  466. void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
  467. const MachineInstr *MI = SU->getInstr();
  468. assert(!MI->isDebugInstr());
  469. const MachineOperand &MO = MI->getOperand(OperIdx);
  470. Register Reg = MO.getReg();
  471. // Remember the use. Data dependencies will be added when we find the def.
  472. LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO)
  473. : LaneBitmask::getAll();
  474. CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
  475. // Add antidependences to the following defs of the vreg.
  476. for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
  477. CurrentVRegDefs.end())) {
  478. // Ignore defs for unrelated lanes.
  479. LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
  480. if ((PrevDefLaneMask & LaneMask).none())
  481. continue;
  482. if (V2SU.SU == SU)
  483. continue;
  484. V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
  485. }
  486. }
  487. /// Returns true if MI is an instruction we are unable to reason about
  488. /// (like a call or something with unmodeled side effects).
  489. static inline bool isGlobalMemoryObject(AAResults *AA, MachineInstr *MI) {
  490. return MI->isCall() || MI->hasUnmodeledSideEffects() ||
  491. (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad(AA));
  492. }
  493. void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
  494. unsigned Latency) {
  495. if (SUa->getInstr()->mayAlias(AAForDep, *SUb->getInstr(), UseTBAA)) {
  496. SDep Dep(SUa, SDep::MayAliasMem);
  497. Dep.setLatency(Latency);
  498. SUb->addPred(Dep);
  499. }
  500. }
  501. /// Creates an SUnit for each real instruction, numbered in top-down
  502. /// topological order. The instruction order A < B, implies that no edge exists
  503. /// from B to A.
  504. ///
  505. /// Map each real instruction to its SUnit.
  506. ///
  507. /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
  508. /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
  509. /// instead of pointers.
  510. ///
  511. /// MachineScheduler relies on initSUnits numbering the nodes by their order in
  512. /// the original instruction list.
  513. void ScheduleDAGInstrs::initSUnits() {
  514. // We'll be allocating one SUnit for each real instruction in the region,
  515. // which is contained within a basic block.
  516. SUnits.reserve(NumRegionInstrs);
  517. for (MachineInstr &MI : make_range(RegionBegin, RegionEnd)) {
  518. if (MI.isDebugInstr())
  519. continue;
  520. SUnit *SU = newSUnit(&MI);
  521. MISUnitMap[&MI] = SU;
  522. SU->isCall = MI.isCall();
  523. SU->isCommutable = MI.isCommutable();
  524. // Assign the Latency field of SU using target-provided information.
  525. SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
  526. // If this SUnit uses a reserved or unbuffered resource, mark it as such.
  527. //
  528. // Reserved resources block an instruction from issuing and stall the
  529. // entire pipeline. These are identified by BufferSize=0.
  530. //
  531. // Unbuffered resources prevent execution of subsequent instructions that
  532. // require the same resources. This is used for in-order execution pipelines
  533. // within an out-of-order core. These are identified by BufferSize=1.
  534. if (SchedModel.hasInstrSchedModel()) {
  535. const MCSchedClassDesc *SC = getSchedClass(SU);
  536. for (const MCWriteProcResEntry &PRE :
  537. make_range(SchedModel.getWriteProcResBegin(SC),
  538. SchedModel.getWriteProcResEnd(SC))) {
  539. switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
  540. case 0:
  541. SU->hasReservedResource = true;
  542. break;
  543. case 1:
  544. SU->isUnbuffered = true;
  545. break;
  546. default:
  547. break;
  548. }
  549. }
  550. }
  551. }
  552. }
  553. class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
  554. /// Current total number of SUs in map.
  555. unsigned NumNodes = 0;
  556. /// 1 for loads, 0 for stores. (see comment in SUList)
  557. unsigned TrueMemOrderLatency;
  558. public:
  559. Value2SUsMap(unsigned lat = 0) : TrueMemOrderLatency(lat) {}
  560. /// To keep NumNodes up to date, insert() is used instead of
  561. /// this operator w/ push_back().
  562. ValueType &operator[](const SUList &Key) {
  563. llvm_unreachable("Don't use. Use insert() instead."); };
  564. /// Adds SU to the SUList of V. If Map grows huge, reduce its size by calling
  565. /// reduce().
  566. void inline insert(SUnit *SU, ValueType V) {
  567. MapVector::operator[](V).push_back(SU);
  568. NumNodes++;
  569. }
  570. /// Clears the list of SUs mapped to V.
  571. void inline clearList(ValueType V) {
  572. iterator Itr = find(V);
  573. if (Itr != end()) {
  574. assert(NumNodes >= Itr->second.size());
  575. NumNodes -= Itr->second.size();
  576. Itr->second.clear();
  577. }
  578. }
  579. /// Clears map from all contents.
  580. void clear() {
  581. MapVector<ValueType, SUList>::clear();
  582. NumNodes = 0;
  583. }
  584. unsigned inline size() const { return NumNodes; }
  585. /// Counts the number of SUs in this map after a reduction.
  586. void reComputeSize() {
  587. NumNodes = 0;
  588. for (auto &I : *this)
  589. NumNodes += I.second.size();
  590. }
  591. unsigned inline getTrueMemOrderLatency() const {
  592. return TrueMemOrderLatency;
  593. }
  594. void dump();
  595. };
  596. void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
  597. Value2SUsMap &Val2SUsMap) {
  598. for (auto &I : Val2SUsMap)
  599. addChainDependencies(SU, I.second,
  600. Val2SUsMap.getTrueMemOrderLatency());
  601. }
  602. void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
  603. Value2SUsMap &Val2SUsMap,
  604. ValueType V) {
  605. Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
  606. if (Itr != Val2SUsMap.end())
  607. addChainDependencies(SU, Itr->second,
  608. Val2SUsMap.getTrueMemOrderLatency());
  609. }
  610. void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
  611. assert(BarrierChain != nullptr);
  612. for (auto &I : map) {
  613. SUList &sus = I.second;
  614. for (auto *SU : sus)
  615. SU->addPredBarrier(BarrierChain);
  616. }
  617. map.clear();
  618. }
  619. void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
  620. assert(BarrierChain != nullptr);
  621. // Go through all lists of SUs.
  622. for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
  623. Value2SUsMap::iterator CurrItr = I++;
  624. SUList &sus = CurrItr->second;
  625. SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
  626. for (; SUItr != SUEE; ++SUItr) {
  627. // Stop on BarrierChain or any instruction above it.
  628. if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
  629. break;
  630. (*SUItr)->addPredBarrier(BarrierChain);
  631. }
  632. // Remove also the BarrierChain from list if present.
  633. if (SUItr != SUEE && *SUItr == BarrierChain)
  634. SUItr++;
  635. // Remove all SUs that are now successors of BarrierChain.
  636. if (SUItr != sus.begin())
  637. sus.erase(sus.begin(), SUItr);
  638. }
  639. // Remove all entries with empty su lists.
  640. map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
  641. return (mapEntry.second.empty()); });
  642. // Recompute the size of the map (NumNodes).
  643. map.reComputeSize();
  644. }
  645. void ScheduleDAGInstrs::buildSchedGraph(AAResults *AA,
  646. RegPressureTracker *RPTracker,
  647. PressureDiffs *PDiffs,
  648. LiveIntervals *LIS,
  649. bool TrackLaneMasks) {
  650. const TargetSubtargetInfo &ST = MF.getSubtarget();
  651. bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
  652. : ST.useAA();
  653. AAForDep = UseAA ? AA : nullptr;
  654. BarrierChain = nullptr;
  655. this->TrackLaneMasks = TrackLaneMasks;
  656. MISUnitMap.clear();
  657. ScheduleDAG::clearDAG();
  658. // Create an SUnit for each real instruction.
  659. initSUnits();
  660. if (PDiffs)
  661. PDiffs->init(SUnits.size());
  662. // We build scheduling units by walking a block's instruction list
  663. // from bottom to top.
  664. // Each MIs' memory operand(s) is analyzed to a list of underlying
  665. // objects. The SU is then inserted in the SUList(s) mapped from the
  666. // Value(s). Each Value thus gets mapped to lists of SUs depending
  667. // on it, stores and loads kept separately. Two SUs are trivially
  668. // non-aliasing if they both depend on only identified Values and do
  669. // not share any common Value.
  670. Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
  671. // Certain memory accesses are known to not alias any SU in Stores
  672. // or Loads, and have therefore their own 'NonAlias'
  673. // domain. E.g. spill / reload instructions never alias LLVM I/R
  674. // Values. It would be nice to assume that this type of memory
  675. // accesses always have a proper memory operand modelling, and are
  676. // therefore never unanalyzable, but this is conservatively not
  677. // done.
  678. Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
  679. // Track all instructions that may raise floating-point exceptions.
  680. // These do not depend on one other (or normal loads or stores), but
  681. // must not be rescheduled across global barriers. Note that we don't
  682. // really need a "map" here since we don't track those MIs by value;
  683. // using the same Value2SUsMap data type here is simply a matter of
  684. // convenience.
  685. Value2SUsMap FPExceptions;
  686. // Remove any stale debug info; sometimes BuildSchedGraph is called again
  687. // without emitting the info from the previous call.
  688. DbgValues.clear();
  689. FirstDbgValue = nullptr;
  690. assert(Defs.empty() && Uses.empty() &&
  691. "Only BuildGraph should update Defs/Uses");
  692. Defs.setUniverse(TRI->getNumRegs());
  693. Uses.setUniverse(TRI->getNumRegs());
  694. assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
  695. assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
  696. unsigned NumVirtRegs = MRI.getNumVirtRegs();
  697. CurrentVRegDefs.setUniverse(NumVirtRegs);
  698. CurrentVRegUses.setUniverse(NumVirtRegs);
  699. // Model data dependencies between instructions being scheduled and the
  700. // ExitSU.
  701. addSchedBarrierDeps();
  702. // Walk the list of instructions, from bottom moving up.
  703. MachineInstr *DbgMI = nullptr;
  704. for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
  705. MII != MIE; --MII) {
  706. MachineInstr &MI = *std::prev(MII);
  707. if (DbgMI) {
  708. DbgValues.push_back(std::make_pair(DbgMI, &MI));
  709. DbgMI = nullptr;
  710. }
  711. if (MI.isDebugValue() || MI.isDebugRef()) {
  712. DbgMI = &MI;
  713. continue;
  714. }
  715. if (MI.isDebugLabel())
  716. continue;
  717. SUnit *SU = MISUnitMap[&MI];
  718. assert(SU && "No SUnit mapped to this MI");
  719. if (RPTracker) {
  720. RegisterOperands RegOpers;
  721. RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
  722. if (TrackLaneMasks) {
  723. SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
  724. RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
  725. }
  726. if (PDiffs != nullptr)
  727. PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
  728. if (RPTracker->getPos() == RegionEnd || &*RPTracker->getPos() != &MI)
  729. RPTracker->recedeSkipDebugValues();
  730. assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
  731. RPTracker->recede(RegOpers);
  732. }
  733. assert(
  734. (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
  735. "Cannot schedule terminators or labels!");
  736. // Add register-based dependencies (data, anti, and output).
  737. // For some instructions (calls, returns, inline-asm, etc.) there can
  738. // be explicit uses and implicit defs, in which case the use will appear
  739. // on the operand list before the def. Do two passes over the operand
  740. // list to make sure that defs are processed before any uses.
  741. bool HasVRegDef = false;
  742. for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
  743. const MachineOperand &MO = MI.getOperand(j);
  744. if (!MO.isReg() || !MO.isDef())
  745. continue;
  746. Register Reg = MO.getReg();
  747. if (Register::isPhysicalRegister(Reg)) {
  748. addPhysRegDeps(SU, j);
  749. } else if (Register::isVirtualRegister(Reg)) {
  750. HasVRegDef = true;
  751. addVRegDefDeps(SU, j);
  752. }
  753. }
  754. // Now process all uses.
  755. for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
  756. const MachineOperand &MO = MI.getOperand(j);
  757. // Only look at use operands.
  758. // We do not need to check for MO.readsReg() here because subsequent
  759. // subregister defs will get output dependence edges and need no
  760. // additional use dependencies.
  761. if (!MO.isReg() || !MO.isUse())
  762. continue;
  763. Register Reg = MO.getReg();
  764. if (Register::isPhysicalRegister(Reg)) {
  765. addPhysRegDeps(SU, j);
  766. } else if (Register::isVirtualRegister(Reg) && MO.readsReg()) {
  767. addVRegUseDeps(SU, j);
  768. }
  769. }
  770. // If we haven't seen any uses in this scheduling region, create a
  771. // dependence edge to ExitSU to model the live-out latency. This is required
  772. // for vreg defs with no in-region use, and prefetches with no vreg def.
  773. //
  774. // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
  775. // check currently relies on being called before adding chain deps.
  776. if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
  777. SDep Dep(SU, SDep::Artificial);
  778. Dep.setLatency(SU->Latency - 1);
  779. ExitSU.addPred(Dep);
  780. }
  781. // Add memory dependencies (Note: isStoreToStackSlot and
  782. // isLoadFromStackSLot are not usable after stack slots are lowered to
  783. // actual addresses).
  784. // This is a barrier event that acts as a pivotal node in the DAG.
  785. if (isGlobalMemoryObject(AA, &MI)) {
  786. // Become the barrier chain.
  787. if (BarrierChain)
  788. BarrierChain->addPredBarrier(SU);
  789. BarrierChain = SU;
  790. LLVM_DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
  791. << BarrierChain->NodeNum << ").\n";);
  792. // Add dependencies against everything below it and clear maps.
  793. addBarrierChain(Stores);
  794. addBarrierChain(Loads);
  795. addBarrierChain(NonAliasStores);
  796. addBarrierChain(NonAliasLoads);
  797. addBarrierChain(FPExceptions);
  798. continue;
  799. }
  800. // Instructions that may raise FP exceptions may not be moved
  801. // across any global barriers.
  802. if (MI.mayRaiseFPException()) {
  803. if (BarrierChain)
  804. BarrierChain->addPredBarrier(SU);
  805. FPExceptions.insert(SU, UnknownValue);
  806. if (FPExceptions.size() >= HugeRegion) {
  807. LLVM_DEBUG(dbgs() << "Reducing FPExceptions map.\n";);
  808. Value2SUsMap empty;
  809. reduceHugeMemNodeMaps(FPExceptions, empty, getReductionSize());
  810. }
  811. }
  812. // If it's not a store or a variant load, we're done.
  813. if (!MI.mayStore() &&
  814. !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
  815. continue;
  816. // Always add dependecy edge to BarrierChain if present.
  817. if (BarrierChain)
  818. BarrierChain->addPredBarrier(SU);
  819. // Find the underlying objects for MI. The Objs vector is either
  820. // empty, or filled with the Values of memory locations which this
  821. // SU depends on.
  822. UnderlyingObjectsVector Objs;
  823. bool ObjsFound = getUnderlyingObjectsForInstr(&MI, MFI, Objs,
  824. MF.getDataLayout());
  825. if (MI.mayStore()) {
  826. if (!ObjsFound) {
  827. // An unknown store depends on all stores and loads.
  828. addChainDependencies(SU, Stores);
  829. addChainDependencies(SU, NonAliasStores);
  830. addChainDependencies(SU, Loads);
  831. addChainDependencies(SU, NonAliasLoads);
  832. // Map this store to 'UnknownValue'.
  833. Stores.insert(SU, UnknownValue);
  834. } else {
  835. // Add precise dependencies against all previously seen memory
  836. // accesses mapped to the same Value(s).
  837. for (const UnderlyingObject &UnderlObj : Objs) {
  838. ValueType V = UnderlObj.getValue();
  839. bool ThisMayAlias = UnderlObj.mayAlias();
  840. // Add dependencies to previous stores and loads mapped to V.
  841. addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
  842. addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
  843. }
  844. // Update the store map after all chains have been added to avoid adding
  845. // self-loop edge if multiple underlying objects are present.
  846. for (const UnderlyingObject &UnderlObj : Objs) {
  847. ValueType V = UnderlObj.getValue();
  848. bool ThisMayAlias = UnderlObj.mayAlias();
  849. // Map this store to V.
  850. (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
  851. }
  852. // The store may have dependencies to unanalyzable loads and
  853. // stores.
  854. addChainDependencies(SU, Loads, UnknownValue);
  855. addChainDependencies(SU, Stores, UnknownValue);
  856. }
  857. } else { // SU is a load.
  858. if (!ObjsFound) {
  859. // An unknown load depends on all stores.
  860. addChainDependencies(SU, Stores);
  861. addChainDependencies(SU, NonAliasStores);
  862. Loads.insert(SU, UnknownValue);
  863. } else {
  864. for (const UnderlyingObject &UnderlObj : Objs) {
  865. ValueType V = UnderlObj.getValue();
  866. bool ThisMayAlias = UnderlObj.mayAlias();
  867. // Add precise dependencies against all previously seen stores
  868. // mapping to the same Value(s).
  869. addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
  870. // Map this load to V.
  871. (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
  872. }
  873. // The load may have dependencies to unanalyzable stores.
  874. addChainDependencies(SU, Stores, UnknownValue);
  875. }
  876. }
  877. // Reduce maps if they grow huge.
  878. if (Stores.size() + Loads.size() >= HugeRegion) {
  879. LLVM_DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
  880. reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
  881. }
  882. if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
  883. LLVM_DEBUG(
  884. dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
  885. reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
  886. }
  887. }
  888. if (DbgMI)
  889. FirstDbgValue = DbgMI;
  890. Defs.clear();
  891. Uses.clear();
  892. CurrentVRegDefs.clear();
  893. CurrentVRegUses.clear();
  894. Topo.MarkDirty();
  895. }
  896. raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
  897. PSV->printCustom(OS);
  898. return OS;
  899. }
  900. void ScheduleDAGInstrs::Value2SUsMap::dump() {
  901. for (auto &Itr : *this) {
  902. if (Itr.first.is<const Value*>()) {
  903. const Value *V = Itr.first.get<const Value*>();
  904. if (isa<UndefValue>(V))
  905. dbgs() << "Unknown";
  906. else
  907. V->printAsOperand(dbgs());
  908. }
  909. else if (Itr.first.is<const PseudoSourceValue*>())
  910. dbgs() << Itr.first.get<const PseudoSourceValue*>();
  911. else
  912. llvm_unreachable("Unknown Value type.");
  913. dbgs() << " : ";
  914. dumpSUList(Itr.second);
  915. }
  916. }
  917. void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
  918. Value2SUsMap &loads, unsigned N) {
  919. LLVM_DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n"; stores.dump();
  920. dbgs() << "Loading SUnits:\n"; loads.dump());
  921. // Insert all SU's NodeNums into a vector and sort it.
  922. std::vector<unsigned> NodeNums;
  923. NodeNums.reserve(stores.size() + loads.size());
  924. for (auto &I : stores)
  925. for (auto *SU : I.second)
  926. NodeNums.push_back(SU->NodeNum);
  927. for (auto &I : loads)
  928. for (auto *SU : I.second)
  929. NodeNums.push_back(SU->NodeNum);
  930. llvm::sort(NodeNums);
  931. // The N last elements in NodeNums will be removed, and the SU with
  932. // the lowest NodeNum of them will become the new BarrierChain to
  933. // let the not yet seen SUs have a dependency to the removed SUs.
  934. assert(N <= NodeNums.size());
  935. SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
  936. if (BarrierChain) {
  937. // The aliasing and non-aliasing maps reduce independently of each
  938. // other, but share a common BarrierChain. Check if the
  939. // newBarrierChain is above the former one. If it is not, it may
  940. // introduce a loop to use newBarrierChain, so keep the old one.
  941. if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
  942. BarrierChain->addPredBarrier(newBarrierChain);
  943. BarrierChain = newBarrierChain;
  944. LLVM_DEBUG(dbgs() << "Inserting new barrier chain: SU("
  945. << BarrierChain->NodeNum << ").\n";);
  946. }
  947. else
  948. LLVM_DEBUG(dbgs() << "Keeping old barrier chain: SU("
  949. << BarrierChain->NodeNum << ").\n";);
  950. }
  951. else
  952. BarrierChain = newBarrierChain;
  953. insertBarrierChain(stores);
  954. insertBarrierChain(loads);
  955. LLVM_DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n"; stores.dump();
  956. dbgs() << "Loading SUnits:\n"; loads.dump());
  957. }
  958. static void toggleKills(const MachineRegisterInfo &MRI, LivePhysRegs &LiveRegs,
  959. MachineInstr &MI, bool addToLiveRegs) {
  960. for (MachineOperand &MO : MI.operands()) {
  961. if (!MO.isReg() || !MO.readsReg())
  962. continue;
  963. Register Reg = MO.getReg();
  964. if (!Reg)
  965. continue;
  966. // Things that are available after the instruction are killed by it.
  967. bool IsKill = LiveRegs.available(MRI, Reg);
  968. MO.setIsKill(IsKill);
  969. if (addToLiveRegs)
  970. LiveRegs.addReg(Reg);
  971. }
  972. }
  973. void ScheduleDAGInstrs::fixupKills(MachineBasicBlock &MBB) {
  974. LLVM_DEBUG(dbgs() << "Fixup kills for " << printMBBReference(MBB) << '\n');
  975. LiveRegs.init(*TRI);
  976. LiveRegs.addLiveOuts(MBB);
  977. // Examine block from end to start...
  978. for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) {
  979. if (MI.isDebugInstr())
  980. continue;
  981. // Update liveness. Registers that are defed but not used in this
  982. // instruction are now dead. Mark register and all subregs as they
  983. // are completely defined.
  984. for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
  985. const MachineOperand &MO = *O;
  986. if (MO.isReg()) {
  987. if (!MO.isDef())
  988. continue;
  989. Register Reg = MO.getReg();
  990. if (!Reg)
  991. continue;
  992. LiveRegs.removeReg(Reg);
  993. } else if (MO.isRegMask()) {
  994. LiveRegs.removeRegsInMask(MO);
  995. }
  996. }
  997. // If there is a bundle header fix it up first.
  998. if (!MI.isBundled()) {
  999. toggleKills(MRI, LiveRegs, MI, true);
  1000. } else {
  1001. MachineBasicBlock::instr_iterator Bundle = MI.getIterator();
  1002. if (MI.isBundle())
  1003. toggleKills(MRI, LiveRegs, MI, false);
  1004. // Some targets make the (questionable) assumtion that the instructions
  1005. // inside the bundle are ordered and consequently only the last use of
  1006. // a register inside the bundle can kill it.
  1007. MachineBasicBlock::instr_iterator I = std::next(Bundle);
  1008. while (I->isBundledWithSucc())
  1009. ++I;
  1010. do {
  1011. if (!I->isDebugInstr())
  1012. toggleKills(MRI, LiveRegs, *I, true);
  1013. --I;
  1014. } while (I != Bundle);
  1015. }
  1016. }
  1017. }
  1018. void ScheduleDAGInstrs::dumpNode(const SUnit &SU) const {
  1019. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1020. dumpNodeName(SU);
  1021. dbgs() << ": ";
  1022. SU.getInstr()->dump();
  1023. #endif
  1024. }
  1025. void ScheduleDAGInstrs::dump() const {
  1026. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1027. if (EntrySU.getInstr() != nullptr)
  1028. dumpNodeAll(EntrySU);
  1029. for (const SUnit &SU : SUnits)
  1030. dumpNodeAll(SU);
  1031. if (ExitSU.getInstr() != nullptr)
  1032. dumpNodeAll(ExitSU);
  1033. #endif
  1034. }
  1035. std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
  1036. std::string s;
  1037. raw_string_ostream oss(s);
  1038. if (SU == &EntrySU)
  1039. oss << "<entry>";
  1040. else if (SU == &ExitSU)
  1041. oss << "<exit>";
  1042. else
  1043. SU->getInstr()->print(oss, /*IsStandalone=*/true);
  1044. return oss.str();
  1045. }
  1046. /// Return the basic block label. It is not necessarilly unique because a block
  1047. /// contains multiple scheduling regions. But it is fine for visualization.
  1048. std::string ScheduleDAGInstrs::getDAGName() const {
  1049. return "dag." + BB->getFullName();
  1050. }
  1051. bool ScheduleDAGInstrs::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
  1052. return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
  1053. }
  1054. bool ScheduleDAGInstrs::addEdge(SUnit *SuccSU, const SDep &PredDep) {
  1055. if (SuccSU != &ExitSU) {
  1056. // Do not use WillCreateCycle, it assumes SD scheduling.
  1057. // If Pred is reachable from Succ, then the edge creates a cycle.
  1058. if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
  1059. return false;
  1060. Topo.AddPredQueued(SuccSU, PredDep.getSUnit());
  1061. }
  1062. SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
  1063. // Return true regardless of whether a new edge needed to be inserted.
  1064. return true;
  1065. }
  1066. //===----------------------------------------------------------------------===//
  1067. // SchedDFSResult Implementation
  1068. //===----------------------------------------------------------------------===//
  1069. namespace llvm {
  1070. /// Internal state used to compute SchedDFSResult.
  1071. class SchedDFSImpl {
  1072. SchedDFSResult &R;
  1073. /// Join DAG nodes into equivalence classes by their subtree.
  1074. IntEqClasses SubtreeClasses;
  1075. /// List PredSU, SuccSU pairs that represent data edges between subtrees.
  1076. std::vector<std::pair<const SUnit *, const SUnit*>> ConnectionPairs;
  1077. struct RootData {
  1078. unsigned NodeID;
  1079. unsigned ParentNodeID; ///< Parent node (member of the parent subtree).
  1080. unsigned SubInstrCount = 0; ///< Instr count in this tree only, not
  1081. /// children.
  1082. RootData(unsigned id): NodeID(id),
  1083. ParentNodeID(SchedDFSResult::InvalidSubtreeID) {}
  1084. unsigned getSparseSetIndex() const { return NodeID; }
  1085. };
  1086. SparseSet<RootData> RootSet;
  1087. public:
  1088. SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
  1089. RootSet.setUniverse(R.DFSNodeData.size());
  1090. }
  1091. /// Returns true if this node been visited by the DFS traversal.
  1092. ///
  1093. /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
  1094. /// ID. Later, SubtreeID is updated but remains valid.
  1095. bool isVisited(const SUnit *SU) const {
  1096. return R.DFSNodeData[SU->NodeNum].SubtreeID
  1097. != SchedDFSResult::InvalidSubtreeID;
  1098. }
  1099. /// Initializes this node's instruction count. We don't need to flag the node
  1100. /// visited until visitPostorder because the DAG cannot have cycles.
  1101. void visitPreorder(const SUnit *SU) {
  1102. R.DFSNodeData[SU->NodeNum].InstrCount =
  1103. SU->getInstr()->isTransient() ? 0 : 1;
  1104. }
  1105. /// Called once for each node after all predecessors are visited. Revisit this
  1106. /// node's predecessors and potentially join them now that we know the ILP of
  1107. /// the other predecessors.
  1108. void visitPostorderNode(const SUnit *SU) {
  1109. // Mark this node as the root of a subtree. It may be joined with its
  1110. // successors later.
  1111. R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
  1112. RootData RData(SU->NodeNum);
  1113. RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
  1114. // If any predecessors are still in their own subtree, they either cannot be
  1115. // joined or are large enough to remain separate. If this parent node's
  1116. // total instruction count is not greater than a child subtree by at least
  1117. // the subtree limit, then try to join it now since splitting subtrees is
  1118. // only useful if multiple high-pressure paths are possible.
  1119. unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
  1120. for (const SDep &PredDep : SU->Preds) {
  1121. if (PredDep.getKind() != SDep::Data)
  1122. continue;
  1123. unsigned PredNum = PredDep.getSUnit()->NodeNum;
  1124. if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
  1125. joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
  1126. // Either link or merge the TreeData entry from the child to the parent.
  1127. if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
  1128. // If the predecessor's parent is invalid, this is a tree edge and the
  1129. // current node is the parent.
  1130. if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
  1131. RootSet[PredNum].ParentNodeID = SU->NodeNum;
  1132. }
  1133. else if (RootSet.count(PredNum)) {
  1134. // The predecessor is not a root, but is still in the root set. This
  1135. // must be the new parent that it was just joined to. Note that
  1136. // RootSet[PredNum].ParentNodeID may either be invalid or may still be
  1137. // set to the original parent.
  1138. RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
  1139. RootSet.erase(PredNum);
  1140. }
  1141. }
  1142. RootSet[SU->NodeNum] = RData;
  1143. }
  1144. /// Called once for each tree edge after calling visitPostOrderNode on
  1145. /// the predecessor. Increment the parent node's instruction count and
  1146. /// preemptively join this subtree to its parent's if it is small enough.
  1147. void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
  1148. R.DFSNodeData[Succ->NodeNum].InstrCount
  1149. += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
  1150. joinPredSubtree(PredDep, Succ);
  1151. }
  1152. /// Adds a connection for cross edges.
  1153. void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
  1154. ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
  1155. }
  1156. /// Sets each node's subtree ID to the representative ID and record
  1157. /// connections between trees.
  1158. void finalize() {
  1159. SubtreeClasses.compress();
  1160. R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
  1161. assert(SubtreeClasses.getNumClasses() == RootSet.size()
  1162. && "number of roots should match trees");
  1163. for (const RootData &Root : RootSet) {
  1164. unsigned TreeID = SubtreeClasses[Root.NodeID];
  1165. if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
  1166. R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
  1167. R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
  1168. // Note that SubInstrCount may be greater than InstrCount if we joined
  1169. // subtrees across a cross edge. InstrCount will be attributed to the
  1170. // original parent, while SubInstrCount will be attributed to the joined
  1171. // parent.
  1172. }
  1173. R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
  1174. R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
  1175. LLVM_DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
  1176. for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
  1177. R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
  1178. LLVM_DEBUG(dbgs() << " SU(" << Idx << ") in tree "
  1179. << R.DFSNodeData[Idx].SubtreeID << '\n');
  1180. }
  1181. for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
  1182. unsigned PredTree = SubtreeClasses[P.first->NodeNum];
  1183. unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
  1184. if (PredTree == SuccTree)
  1185. continue;
  1186. unsigned Depth = P.first->getDepth();
  1187. addConnection(PredTree, SuccTree, Depth);
  1188. addConnection(SuccTree, PredTree, Depth);
  1189. }
  1190. }
  1191. protected:
  1192. /// Joins the predecessor subtree with the successor that is its DFS parent.
  1193. /// Applies some heuristics before joining.
  1194. bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
  1195. bool CheckLimit = true) {
  1196. assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
  1197. // Check if the predecessor is already joined.
  1198. const SUnit *PredSU = PredDep.getSUnit();
  1199. unsigned PredNum = PredSU->NodeNum;
  1200. if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
  1201. return false;
  1202. // Four is the magic number of successors before a node is considered a
  1203. // pinch point.
  1204. unsigned NumDataSucs = 0;
  1205. for (const SDep &SuccDep : PredSU->Succs) {
  1206. if (SuccDep.getKind() == SDep::Data) {
  1207. if (++NumDataSucs >= 4)
  1208. return false;
  1209. }
  1210. }
  1211. if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
  1212. return false;
  1213. R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
  1214. SubtreeClasses.join(Succ->NodeNum, PredNum);
  1215. return true;
  1216. }
  1217. /// Called by finalize() to record a connection between trees.
  1218. void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
  1219. if (!Depth)
  1220. return;
  1221. do {
  1222. SmallVectorImpl<SchedDFSResult::Connection> &Connections =
  1223. R.SubtreeConnections[FromTree];
  1224. for (SchedDFSResult::Connection &C : Connections) {
  1225. if (C.TreeID == ToTree) {
  1226. C.Level = std::max(C.Level, Depth);
  1227. return;
  1228. }
  1229. }
  1230. Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
  1231. FromTree = R.DFSTreeData[FromTree].ParentTreeID;
  1232. } while (FromTree != SchedDFSResult::InvalidSubtreeID);
  1233. }
  1234. };
  1235. } // end namespace llvm
  1236. namespace {
  1237. /// Manage the stack used by a reverse depth-first search over the DAG.
  1238. class SchedDAGReverseDFS {
  1239. std::vector<std::pair<const SUnit *, SUnit::const_pred_iterator>> DFSStack;
  1240. public:
  1241. bool isComplete() const { return DFSStack.empty(); }
  1242. void follow(const SUnit *SU) {
  1243. DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
  1244. }
  1245. void advance() { ++DFSStack.back().second; }
  1246. const SDep *backtrack() {
  1247. DFSStack.pop_back();
  1248. return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
  1249. }
  1250. const SUnit *getCurr() const { return DFSStack.back().first; }
  1251. SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
  1252. SUnit::const_pred_iterator getPredEnd() const {
  1253. return getCurr()->Preds.end();
  1254. }
  1255. };
  1256. } // end anonymous namespace
  1257. static bool hasDataSucc(const SUnit *SU) {
  1258. for (const SDep &SuccDep : SU->Succs) {
  1259. if (SuccDep.getKind() == SDep::Data &&
  1260. !SuccDep.getSUnit()->isBoundaryNode())
  1261. return true;
  1262. }
  1263. return false;
  1264. }
  1265. /// Computes an ILP metric for all nodes in the subDAG reachable via depth-first
  1266. /// search from this root.
  1267. void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
  1268. if (!IsBottomUp)
  1269. llvm_unreachable("Top-down ILP metric is unimplemented");
  1270. SchedDFSImpl Impl(*this);
  1271. for (const SUnit &SU : SUnits) {
  1272. if (Impl.isVisited(&SU) || hasDataSucc(&SU))
  1273. continue;
  1274. SchedDAGReverseDFS DFS;
  1275. Impl.visitPreorder(&SU);
  1276. DFS.follow(&SU);
  1277. while (true) {
  1278. // Traverse the leftmost path as far as possible.
  1279. while (DFS.getPred() != DFS.getPredEnd()) {
  1280. const SDep &PredDep = *DFS.getPred();
  1281. DFS.advance();
  1282. // Ignore non-data edges.
  1283. if (PredDep.getKind() != SDep::Data
  1284. || PredDep.getSUnit()->isBoundaryNode()) {
  1285. continue;
  1286. }
  1287. // An already visited edge is a cross edge, assuming an acyclic DAG.
  1288. if (Impl.isVisited(PredDep.getSUnit())) {
  1289. Impl.visitCrossEdge(PredDep, DFS.getCurr());
  1290. continue;
  1291. }
  1292. Impl.visitPreorder(PredDep.getSUnit());
  1293. DFS.follow(PredDep.getSUnit());
  1294. }
  1295. // Visit the top of the stack in postorder and backtrack.
  1296. const SUnit *Child = DFS.getCurr();
  1297. const SDep *PredDep = DFS.backtrack();
  1298. Impl.visitPostorderNode(Child);
  1299. if (PredDep)
  1300. Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
  1301. if (DFS.isComplete())
  1302. break;
  1303. }
  1304. }
  1305. Impl.finalize();
  1306. }
  1307. /// The root of the given SubtreeID was just scheduled. For all subtrees
  1308. /// connected to this tree, record the depth of the connection so that the
  1309. /// nearest connected subtrees can be prioritized.
  1310. void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
  1311. for (const Connection &C : SubtreeConnections[SubtreeID]) {
  1312. SubtreeConnectLevels[C.TreeID] =
  1313. std::max(SubtreeConnectLevels[C.TreeID], C.Level);
  1314. LLVM_DEBUG(dbgs() << " Tree: " << C.TreeID << " @"
  1315. << SubtreeConnectLevels[C.TreeID] << '\n');
  1316. }
  1317. }
  1318. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1319. LLVM_DUMP_METHOD void ILPValue::print(raw_ostream &OS) const {
  1320. OS << InstrCount << " / " << Length << " = ";
  1321. if (!Length)
  1322. OS << "BADILP";
  1323. else
  1324. OS << format("%g", ((double)InstrCount / Length));
  1325. }
  1326. LLVM_DUMP_METHOD void ILPValue::dump() const {
  1327. dbgs() << *this << '\n';
  1328. }
  1329. namespace llvm {
  1330. LLVM_DUMP_METHOD
  1331. raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
  1332. Val.print(OS);
  1333. return OS;
  1334. }
  1335. } // end namespace llvm
  1336. #endif