ScheduleDAGInstrs.cpp 54 KB

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