ScheduleDAGInstrs.cpp 53 KB

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