TargetSchedule.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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/MachineFunction.h"
  15. #include "llvm/CodeGen/MachineInstr.h"
  16. #include "llvm/CodeGen/MachineOperand.h"
  17. #include "llvm/CodeGen/TargetSchedule.h"
  18. #include "llvm/MC/MCInstrDesc.h"
  19. #include "llvm/MC/MCInstrItineraries.h"
  20. #include "llvm/MC/MCSchedule.h"
  21. #include "llvm/Support/CommandLine.h"
  22. #include "llvm/Support/ErrorHandling.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include "llvm/Target/TargetInstrInfo.h"
  25. #include "llvm/Target/TargetRegisterInfo.h"
  26. #include "llvm/Target/TargetSubtargetInfo.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 MCSchedModel &sm,
  56. const TargetSubtargetInfo *sti,
  57. const TargetInstrInfo *tii) {
  58. SchedModel = sm;
  59. STI = sti;
  60. TII = tii;
  61. STI->initInstrItins(InstrItins);
  62. unsigned NumRes = SchedModel.getNumProcResourceKinds();
  63. ResourceFactors.resize(NumRes);
  64. ResourceLCM = SchedModel.IssueWidth;
  65. for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
  66. unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
  67. if (NumUnits > 0)
  68. ResourceLCM = lcm(ResourceLCM, NumUnits);
  69. }
  70. MicroOpFactor = ResourceLCM / SchedModel.IssueWidth;
  71. for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
  72. unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
  73. ResourceFactors[Idx] = NumUnits ? (ResourceLCM / NumUnits) : 0;
  74. }
  75. }
  76. unsigned TargetSchedModel::getNumMicroOps(const MachineInstr *MI,
  77. const MCSchedClassDesc *SC) const {
  78. if (hasInstrItineraries()) {
  79. int UOps = InstrItins.getNumMicroOps(MI->getDesc().getSchedClass());
  80. return (UOps >= 0) ? UOps : TII->getNumMicroOps(&InstrItins, *MI);
  81. }
  82. if (hasInstrSchedModel()) {
  83. if (!SC)
  84. SC = resolveSchedClass(MI);
  85. if (SC->isValid())
  86. return SC->NumMicroOps;
  87. }
  88. return MI->isTransient() ? 0 : 1;
  89. }
  90. // The machine model may explicitly specify an invalid latency, which
  91. // effectively means infinite latency. Since users of the TargetSchedule API
  92. // don't know how to handle this, we convert it to a very large latency that is
  93. // easy to distinguish when debugging the DAG but won't induce overflow.
  94. static unsigned capLatency(int Cycles) {
  95. return Cycles >= 0 ? Cycles : 1000;
  96. }
  97. /// Return the MCSchedClassDesc for this instruction. Some SchedClasses require
  98. /// evaluation of predicates that depend on instruction operands or flags.
  99. const MCSchedClassDesc *TargetSchedModel::
  100. resolveSchedClass(const MachineInstr *MI) const {
  101. // Get the definition's scheduling class descriptor from this machine model.
  102. unsigned SchedClass = MI->getDesc().getSchedClass();
  103. const MCSchedClassDesc *SCDesc = SchedModel.getSchedClassDesc(SchedClass);
  104. if (!SCDesc->isValid())
  105. return SCDesc;
  106. #ifndef NDEBUG
  107. unsigned NIter = 0;
  108. #endif
  109. while (SCDesc->isVariant()) {
  110. assert(++NIter < 6 && "Variants are nested deeper than the magic number");
  111. SchedClass = STI->resolveSchedClass(SchedClass, MI, this);
  112. SCDesc = SchedModel.getSchedClassDesc(SchedClass);
  113. }
  114. return SCDesc;
  115. }
  116. /// Find the def index of this operand. This index maps to the machine model and
  117. /// is independent of use operands. Def operands may be reordered with uses or
  118. /// merged with uses without affecting the def index (e.g. before/after
  119. /// regalloc). However, an instruction's def operands must never be reordered
  120. /// with respect to each other.
  121. static unsigned findDefIdx(const MachineInstr *MI, unsigned DefOperIdx) {
  122. unsigned DefIdx = 0;
  123. for (unsigned i = 0; i != DefOperIdx; ++i) {
  124. const MachineOperand &MO = MI->getOperand(i);
  125. if (MO.isReg() && MO.isDef())
  126. ++DefIdx;
  127. }
  128. return DefIdx;
  129. }
  130. /// Find the use index of this operand. This is independent of the instruction's
  131. /// def operands.
  132. ///
  133. /// Note that uses are not determined by the operand's isUse property, which
  134. /// is simply the inverse of isDef. Here we consider any readsReg operand to be
  135. /// a "use". The machine model allows an operand to be both a Def and Use.
  136. static unsigned findUseIdx(const MachineInstr *MI, unsigned UseOperIdx) {
  137. unsigned UseIdx = 0;
  138. for (unsigned i = 0; i != UseOperIdx; ++i) {
  139. const MachineOperand &MO = MI->getOperand(i);
  140. if (MO.isReg() && MO.readsReg() && !MO.isDef())
  141. ++UseIdx;
  142. }
  143. return UseIdx;
  144. }
  145. // Top-level API for clients that know the operand indices.
  146. unsigned TargetSchedModel::computeOperandLatency(
  147. const MachineInstr *DefMI, unsigned DefOperIdx,
  148. const MachineInstr *UseMI, unsigned UseOperIdx) const {
  149. if (!hasInstrSchedModel() && !hasInstrItineraries())
  150. return TII->defaultDefLatency(SchedModel, *DefMI);
  151. if (hasInstrItineraries()) {
  152. int OperLatency = 0;
  153. if (UseMI) {
  154. OperLatency = TII->getOperandLatency(&InstrItins, *DefMI, DefOperIdx,
  155. *UseMI, UseOperIdx);
  156. }
  157. else {
  158. unsigned DefClass = DefMI->getDesc().getSchedClass();
  159. OperLatency = InstrItins.getOperandCycle(DefClass, DefOperIdx);
  160. }
  161. if (OperLatency >= 0)
  162. return OperLatency;
  163. // No operand latency was found.
  164. unsigned InstrLatency = TII->getInstrLatency(&InstrItins, *DefMI);
  165. // Expected latency is the max of the stage latency and itinerary props.
  166. // Rather than directly querying InstrItins stage latency, we call a TII
  167. // hook to allow subtargets to specialize latency. This hook is only
  168. // applicable to the InstrItins model. InstrSchedModel should model all
  169. // special cases without TII hooks.
  170. InstrLatency =
  171. std::max(InstrLatency, TII->defaultDefLatency(SchedModel, *DefMI));
  172. return InstrLatency;
  173. }
  174. // hasInstrSchedModel()
  175. const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
  176. unsigned DefIdx = findDefIdx(DefMI, DefOperIdx);
  177. if (DefIdx < SCDesc->NumWriteLatencyEntries) {
  178. // Lookup the definition's write latency in SubtargetInfo.
  179. const MCWriteLatencyEntry *WLEntry =
  180. STI->getWriteLatencyEntry(SCDesc, DefIdx);
  181. unsigned WriteID = WLEntry->WriteResourceID;
  182. unsigned Latency = capLatency(WLEntry->Cycles);
  183. if (!UseMI)
  184. return Latency;
  185. // Lookup the use's latency adjustment in SubtargetInfo.
  186. const MCSchedClassDesc *UseDesc = resolveSchedClass(UseMI);
  187. if (UseDesc->NumReadAdvanceEntries == 0)
  188. return Latency;
  189. unsigned UseIdx = findUseIdx(UseMI, UseOperIdx);
  190. int Advance = STI->getReadAdvanceCycles(UseDesc, UseIdx, WriteID);
  191. if (Advance > 0 && (unsigned)Advance > Latency) // unsigned wrap
  192. return 0;
  193. return Latency - Advance;
  194. }
  195. // If DefIdx does not exist in the model (e.g. implicit defs), then return
  196. // unit latency (defaultDefLatency may be too conservative).
  197. #ifndef NDEBUG
  198. if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit()
  199. && !DefMI->getDesc().OpInfo[DefOperIdx].isOptionalDef()
  200. && SchedModel.isComplete()) {
  201. errs() << "DefIdx " << DefIdx << " exceeds machine model writes for "
  202. << *DefMI << " (Try with MCSchedModel.CompleteModel set to false)";
  203. llvm_unreachable("incomplete machine model");
  204. }
  205. #endif
  206. // FIXME: Automatically giving all implicit defs defaultDefLatency is
  207. // undesirable. We should only do it for defs that are known to the MC
  208. // desc like flags. Truly implicit defs should get 1 cycle latency.
  209. return DefMI->isTransient() ? 0 : TII->defaultDefLatency(SchedModel, *DefMI);
  210. }
  211. unsigned
  212. TargetSchedModel::computeInstrLatency(const MCSchedClassDesc &SCDesc) const {
  213. unsigned Latency = 0;
  214. for (unsigned DefIdx = 0, DefEnd = SCDesc.NumWriteLatencyEntries;
  215. DefIdx != DefEnd; ++DefIdx) {
  216. // Lookup the definition's write latency in SubtargetInfo.
  217. const MCWriteLatencyEntry *WLEntry =
  218. STI->getWriteLatencyEntry(&SCDesc, DefIdx);
  219. Latency = std::max(Latency, capLatency(WLEntry->Cycles));
  220. }
  221. return Latency;
  222. }
  223. unsigned TargetSchedModel::computeInstrLatency(unsigned Opcode) const {
  224. assert(hasInstrSchedModel() && "Only call this function with a SchedModel");
  225. unsigned SCIdx = TII->get(Opcode).getSchedClass();
  226. const MCSchedClassDesc *SCDesc = SchedModel.getSchedClassDesc(SCIdx);
  227. if (SCDesc->isValid() && !SCDesc->isVariant())
  228. return computeInstrLatency(*SCDesc);
  229. llvm_unreachable("No MI sched latency");
  230. }
  231. unsigned
  232. TargetSchedModel::computeInstrLatency(const MachineInstr *MI,
  233. bool UseDefaultDefLatency) const {
  234. // For the itinerary model, fall back to the old subtarget hook.
  235. // Allow subtargets to compute Bundle latencies outside the machine model.
  236. if (hasInstrItineraries() || MI->isBundle() ||
  237. (!hasInstrSchedModel() && !UseDefaultDefLatency))
  238. return TII->getInstrLatency(&InstrItins, *MI);
  239. if (hasInstrSchedModel()) {
  240. const MCSchedClassDesc *SCDesc = resolveSchedClass(MI);
  241. if (SCDesc->isValid())
  242. return computeInstrLatency(*SCDesc);
  243. }
  244. return TII->defaultDefLatency(SchedModel, *MI);
  245. }
  246. unsigned TargetSchedModel::
  247. computeOutputLatency(const MachineInstr *DefMI, unsigned DefOperIdx,
  248. const MachineInstr *DepMI) const {
  249. if (!SchedModel.isOutOfOrder())
  250. return 1;
  251. // Out-of-order processor can dispatch WAW dependencies in the same cycle.
  252. // Treat predication as a data dependency for out-of-order cpus. In-order
  253. // cpus do not need to treat predicated writes specially.
  254. //
  255. // TODO: The following hack exists because predication passes do not
  256. // correctly append imp-use operands, and readsReg() strangely returns false
  257. // for predicated defs.
  258. unsigned Reg = DefMI->getOperand(DefOperIdx).getReg();
  259. const MachineFunction &MF = *DefMI->getParent()->getParent();
  260. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  261. if (!DepMI->readsRegister(Reg, TRI) && TII->isPredicated(*DepMI))
  262. return computeInstrLatency(DefMI);
  263. // If we have a per operand scheduling model, check if this def is writing
  264. // an unbuffered resource. If so, it treated like an in-order cpu.
  265. if (hasInstrSchedModel()) {
  266. const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
  267. if (SCDesc->isValid()) {
  268. for (const MCWriteProcResEntry *PRI = STI->getWriteProcResBegin(SCDesc),
  269. *PRE = STI->getWriteProcResEnd(SCDesc); PRI != PRE; ++PRI) {
  270. if (!SchedModel.getProcResource(PRI->ProcResourceIdx)->BufferSize)
  271. return 1;
  272. }
  273. }
  274. }
  275. return 0;
  276. }