TargetSchedule.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. //===- llvm/Target/TargetSchedule.cpp - Sched Machine Model ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements a wrapper around MCSchedModel that allows the interface
  11. // to benefit from information currently only available in TargetInstrInfo.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/TargetSchedule.h"
  15. #include "llvm/CodeGen/MachineFunction.h"
  16. #include "llvm/CodeGen/MachineInstr.h"
  17. #include "llvm/CodeGen/MachineOperand.h"
  18. #include "llvm/CodeGen/TargetInstrInfo.h"
  19. #include "llvm/CodeGen/TargetRegisterInfo.h"
  20. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  21. #include "llvm/MC/MCInstrDesc.h"
  22. #include "llvm/MC/MCInstrItineraries.h"
  23. #include "llvm/MC/MCSchedule.h"
  24. #include "llvm/Support/CommandLine.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm>
  28. #include <cassert>
  29. #include <cstdint>
  30. using namespace llvm;
  31. static cl::opt<bool> EnableSchedModel("schedmodel", cl::Hidden, cl::init(true),
  32. cl::desc("Use TargetSchedModel for latency lookup"));
  33. static cl::opt<bool> EnableSchedItins("scheditins", cl::Hidden, cl::init(true),
  34. cl::desc("Use InstrItineraryData for latency lookup"));
  35. bool TargetSchedModel::hasInstrSchedModel() const {
  36. return EnableSchedModel && SchedModel.hasInstrSchedModel();
  37. }
  38. bool TargetSchedModel::hasInstrItineraries() const {
  39. return EnableSchedItins && !InstrItins.isEmpty();
  40. }
  41. static unsigned gcd(unsigned Dividend, unsigned Divisor) {
  42. // Dividend and Divisor will be naturally swapped as needed.
  43. while (Divisor) {
  44. unsigned Rem = Dividend % Divisor;
  45. Dividend = Divisor;
  46. Divisor = Rem;
  47. };
  48. return Dividend;
  49. }
  50. static unsigned lcm(unsigned A, unsigned B) {
  51. unsigned LCM = (uint64_t(A) * B) / gcd(A, B);
  52. assert((LCM >= A && LCM >= B) && "LCM overflow");
  53. return LCM;
  54. }
  55. void TargetSchedModel::init(const TargetSubtargetInfo *TSInfo) {
  56. STI = TSInfo;
  57. SchedModel = TSInfo->getSchedModel();
  58. TII = TSInfo->getInstrInfo();
  59. STI->initInstrItins(InstrItins);
  60. unsigned NumRes = SchedModel.getNumProcResourceKinds();
  61. ResourceFactors.resize(NumRes);
  62. ResourceLCM = SchedModel.IssueWidth;
  63. for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
  64. unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
  65. if (NumUnits > 0)
  66. ResourceLCM = lcm(ResourceLCM, NumUnits);
  67. }
  68. MicroOpFactor = ResourceLCM / SchedModel.IssueWidth;
  69. for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
  70. unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
  71. ResourceFactors[Idx] = NumUnits ? (ResourceLCM / NumUnits) : 0;
  72. }
  73. }
  74. /// Returns true only if instruction is specified as single issue.
  75. bool TargetSchedModel::mustBeginGroup(const MachineInstr *MI,
  76. const MCSchedClassDesc *SC) const {
  77. if (hasInstrSchedModel()) {
  78. if (!SC)
  79. SC = resolveSchedClass(MI);
  80. if (SC->isValid())
  81. return SC->BeginGroup;
  82. }
  83. return false;
  84. }
  85. bool TargetSchedModel::mustEndGroup(const MachineInstr *MI,
  86. const MCSchedClassDesc *SC) const {
  87. if (hasInstrSchedModel()) {
  88. if (!SC)
  89. SC = resolveSchedClass(MI);
  90. if (SC->isValid())
  91. return SC->EndGroup;
  92. }
  93. return false;
  94. }
  95. unsigned TargetSchedModel::getNumMicroOps(const MachineInstr *MI,
  96. const MCSchedClassDesc *SC) const {
  97. if (hasInstrItineraries()) {
  98. int UOps = InstrItins.getNumMicroOps(MI->getDesc().getSchedClass());
  99. return (UOps >= 0) ? UOps : TII->getNumMicroOps(&InstrItins, *MI);
  100. }
  101. if (hasInstrSchedModel()) {
  102. if (!SC)
  103. SC = resolveSchedClass(MI);
  104. if (SC->isValid())
  105. return SC->NumMicroOps;
  106. }
  107. return MI->isTransient() ? 0 : 1;
  108. }
  109. // The machine model may explicitly specify an invalid latency, which
  110. // effectively means infinite latency. Since users of the TargetSchedule API
  111. // don't know how to handle this, we convert it to a very large latency that is
  112. // easy to distinguish when debugging the DAG but won't induce overflow.
  113. static unsigned capLatency(int Cycles) {
  114. return Cycles >= 0 ? Cycles : 1000;
  115. }
  116. /// Return the MCSchedClassDesc for this instruction. Some SchedClasses require
  117. /// evaluation of predicates that depend on instruction operands or flags.
  118. const MCSchedClassDesc *TargetSchedModel::
  119. resolveSchedClass(const MachineInstr *MI) const {
  120. // Get the definition's scheduling class descriptor from this machine model.
  121. unsigned SchedClass = MI->getDesc().getSchedClass();
  122. const MCSchedClassDesc *SCDesc = SchedModel.getSchedClassDesc(SchedClass);
  123. if (!SCDesc->isValid())
  124. return SCDesc;
  125. #ifndef NDEBUG
  126. unsigned NIter = 0;
  127. #endif
  128. while (SCDesc->isVariant()) {
  129. assert(++NIter < 6 && "Variants are nested deeper than the magic number");
  130. SchedClass = STI->resolveSchedClass(SchedClass, MI, this);
  131. SCDesc = SchedModel.getSchedClassDesc(SchedClass);
  132. }
  133. return SCDesc;
  134. }
  135. /// Find the def index of this operand. This index maps to the machine model and
  136. /// is independent of use operands. Def operands may be reordered with uses or
  137. /// merged with uses without affecting the def index (e.g. before/after
  138. /// regalloc). However, an instruction's def operands must never be reordered
  139. /// with respect to each other.
  140. static unsigned findDefIdx(const MachineInstr *MI, unsigned DefOperIdx) {
  141. unsigned DefIdx = 0;
  142. for (unsigned i = 0; i != DefOperIdx; ++i) {
  143. const MachineOperand &MO = MI->getOperand(i);
  144. if (MO.isReg() && MO.isDef())
  145. ++DefIdx;
  146. }
  147. return DefIdx;
  148. }
  149. /// Find the use index of this operand. This is independent of the instruction's
  150. /// def operands.
  151. ///
  152. /// Note that uses are not determined by the operand's isUse property, which
  153. /// is simply the inverse of isDef. Here we consider any readsReg operand to be
  154. /// a "use". The machine model allows an operand to be both a Def and Use.
  155. static unsigned findUseIdx(const MachineInstr *MI, unsigned UseOperIdx) {
  156. unsigned UseIdx = 0;
  157. for (unsigned i = 0; i != UseOperIdx; ++i) {
  158. const MachineOperand &MO = MI->getOperand(i);
  159. if (MO.isReg() && MO.readsReg() && !MO.isDef())
  160. ++UseIdx;
  161. }
  162. return UseIdx;
  163. }
  164. // Top-level API for clients that know the operand indices.
  165. unsigned TargetSchedModel::computeOperandLatency(
  166. const MachineInstr *DefMI, unsigned DefOperIdx,
  167. const MachineInstr *UseMI, unsigned UseOperIdx) const {
  168. if (!hasInstrSchedModel() && !hasInstrItineraries())
  169. return TII->defaultDefLatency(SchedModel, *DefMI);
  170. if (hasInstrItineraries()) {
  171. int OperLatency = 0;
  172. if (UseMI) {
  173. OperLatency = TII->getOperandLatency(&InstrItins, *DefMI, DefOperIdx,
  174. *UseMI, UseOperIdx);
  175. }
  176. else {
  177. unsigned DefClass = DefMI->getDesc().getSchedClass();
  178. OperLatency = InstrItins.getOperandCycle(DefClass, DefOperIdx);
  179. }
  180. if (OperLatency >= 0)
  181. return OperLatency;
  182. // No operand latency was found.
  183. unsigned InstrLatency = TII->getInstrLatency(&InstrItins, *DefMI);
  184. // Expected latency is the max of the stage latency and itinerary props.
  185. // Rather than directly querying InstrItins stage latency, we call a TII
  186. // hook to allow subtargets to specialize latency. This hook is only
  187. // applicable to the InstrItins model. InstrSchedModel should model all
  188. // special cases without TII hooks.
  189. InstrLatency =
  190. std::max(InstrLatency, TII->defaultDefLatency(SchedModel, *DefMI));
  191. return InstrLatency;
  192. }
  193. // hasInstrSchedModel()
  194. const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
  195. unsigned DefIdx = findDefIdx(DefMI, DefOperIdx);
  196. if (DefIdx < SCDesc->NumWriteLatencyEntries) {
  197. // Lookup the definition's write latency in SubtargetInfo.
  198. const MCWriteLatencyEntry *WLEntry =
  199. STI->getWriteLatencyEntry(SCDesc, DefIdx);
  200. unsigned WriteID = WLEntry->WriteResourceID;
  201. unsigned Latency = capLatency(WLEntry->Cycles);
  202. if (!UseMI)
  203. return Latency;
  204. // Lookup the use's latency adjustment in SubtargetInfo.
  205. const MCSchedClassDesc *UseDesc = resolveSchedClass(UseMI);
  206. if (UseDesc->NumReadAdvanceEntries == 0)
  207. return Latency;
  208. unsigned UseIdx = findUseIdx(UseMI, UseOperIdx);
  209. int Advance = STI->getReadAdvanceCycles(UseDesc, UseIdx, WriteID);
  210. if (Advance > 0 && (unsigned)Advance > Latency) // unsigned wrap
  211. return 0;
  212. return Latency - Advance;
  213. }
  214. // If DefIdx does not exist in the model (e.g. implicit defs), then return
  215. // unit latency (defaultDefLatency may be too conservative).
  216. #ifndef NDEBUG
  217. if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit()
  218. && !DefMI->getDesc().OpInfo[DefOperIdx].isOptionalDef()
  219. && SchedModel.isComplete()) {
  220. errs() << "DefIdx " << DefIdx << " exceeds machine model writes for "
  221. << *DefMI << " (Try with MCSchedModel.CompleteModel set to false)";
  222. llvm_unreachable("incomplete machine model");
  223. }
  224. #endif
  225. // FIXME: Automatically giving all implicit defs defaultDefLatency is
  226. // undesirable. We should only do it for defs that are known to the MC
  227. // desc like flags. Truly implicit defs should get 1 cycle latency.
  228. return DefMI->isTransient() ? 0 : TII->defaultDefLatency(SchedModel, *DefMI);
  229. }
  230. unsigned
  231. TargetSchedModel::computeInstrLatency(const MCSchedClassDesc &SCDesc) const {
  232. return capLatency(MCSchedModel::computeInstrLatency(*STI, SCDesc));
  233. }
  234. unsigned TargetSchedModel::computeInstrLatency(unsigned Opcode) const {
  235. assert(hasInstrSchedModel() && "Only call this function with a SchedModel");
  236. unsigned SCIdx = TII->get(Opcode).getSchedClass();
  237. return SchedModel.computeInstrLatency(*STI, SCIdx);
  238. }
  239. unsigned
  240. TargetSchedModel::computeInstrLatency(const MachineInstr *MI,
  241. bool UseDefaultDefLatency) const {
  242. // For the itinerary model, fall back to the old subtarget hook.
  243. // Allow subtargets to compute Bundle latencies outside the machine model.
  244. if (hasInstrItineraries() || MI->isBundle() ||
  245. (!hasInstrSchedModel() && !UseDefaultDefLatency))
  246. return TII->getInstrLatency(&InstrItins, *MI);
  247. if (hasInstrSchedModel()) {
  248. const MCSchedClassDesc *SCDesc = resolveSchedClass(MI);
  249. if (SCDesc->isValid())
  250. return computeInstrLatency(*SCDesc);
  251. }
  252. return TII->defaultDefLatency(SchedModel, *MI);
  253. }
  254. unsigned TargetSchedModel::
  255. computeOutputLatency(const MachineInstr *DefMI, unsigned DefOperIdx,
  256. const MachineInstr *DepMI) const {
  257. if (!SchedModel.isOutOfOrder())
  258. return 1;
  259. // Out-of-order processor can dispatch WAW dependencies in the same cycle.
  260. // Treat predication as a data dependency for out-of-order cpus. In-order
  261. // cpus do not need to treat predicated writes specially.
  262. //
  263. // TODO: The following hack exists because predication passes do not
  264. // correctly append imp-use operands, and readsReg() strangely returns false
  265. // for predicated defs.
  266. unsigned Reg = DefMI->getOperand(DefOperIdx).getReg();
  267. const MachineFunction &MF = *DefMI->getMF();
  268. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  269. if (!DepMI->readsRegister(Reg, TRI) && TII->isPredicated(*DepMI))
  270. return computeInstrLatency(DefMI);
  271. // If we have a per operand scheduling model, check if this def is writing
  272. // an unbuffered resource. If so, it treated like an in-order cpu.
  273. if (hasInstrSchedModel()) {
  274. const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
  275. if (SCDesc->isValid()) {
  276. for (const MCWriteProcResEntry *PRI = STI->getWriteProcResBegin(SCDesc),
  277. *PRE = STI->getWriteProcResEnd(SCDesc); PRI != PRE; ++PRI) {
  278. if (!SchedModel.getProcResource(PRI->ProcResourceIdx)->BufferSize)
  279. return 1;
  280. }
  281. }
  282. }
  283. return 0;
  284. }
  285. Optional<double>
  286. TargetSchedModel::computeReciprocalThroughput(const MachineInstr *MI) const {
  287. if (hasInstrItineraries()) {
  288. unsigned SchedClass = MI->getDesc().getSchedClass();
  289. return MCSchedModel::getReciprocalThroughput(SchedClass,
  290. *getInstrItineraries());
  291. }
  292. if (hasInstrSchedModel())
  293. return MCSchedModel::getReciprocalThroughput(*STI, *resolveSchedClass(MI));
  294. return Optional<double>();
  295. }
  296. Optional<double>
  297. TargetSchedModel::computeReciprocalThroughput(unsigned Opcode) const {
  298. unsigned SchedClass = TII->get(Opcode).getSchedClass();
  299. if (hasInstrItineraries())
  300. return MCSchedModel::getReciprocalThroughput(SchedClass,
  301. *getInstrItineraries());
  302. if (hasInstrSchedModel()) {
  303. const MCSchedClassDesc &SCDesc = *SchedModel.getSchedClassDesc(SchedClass);
  304. if (SCDesc.isValid() && !SCDesc.isVariant())
  305. return MCSchedModel::getReciprocalThroughput(*STI, SCDesc);
  306. }
  307. return Optional<double>();
  308. }