MachineTraceMetrics.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- lib/CodeGen/MachineTraceMetrics.h - Super-scalar metrics -*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the interface for the MachineTraceMetrics analysis pass
  15. // that estimates CPU resource usage and critical data dependency paths through
  16. // preferred traces. This is useful for super-scalar CPUs where execution speed
  17. // can be limited both by data dependencies and by limited execution resources.
  18. //
  19. // Out-of-order CPUs will often be executing instructions from multiple basic
  20. // blocks at the same time. This makes it difficult to estimate the resource
  21. // usage accurately in a single basic block. Resources can be estimated better
  22. // by looking at a trace through the current basic block.
  23. //
  24. // For every block, the MachineTraceMetrics pass will pick a preferred trace
  25. // that passes through the block. The trace is chosen based on loop structure,
  26. // branch probabilities, and resource usage. The intention is to pick likely
  27. // traces that would be the most affected by code transformations.
  28. //
  29. // It is expensive to compute a full arbitrary trace for every block, so to
  30. // save some computations, traces are chosen to be convergent. This means that
  31. // if the traces through basic blocks A and B ever cross when moving away from
  32. // A and B, they never diverge again. This applies in both directions - If the
  33. // traces meet above A and B, they won't diverge when going further back.
  34. //
  35. // Traces tend to align with loops. The trace through a block in an inner loop
  36. // will begin at the loop entry block and end at a back edge. If there are
  37. // nested loops, the trace may begin and end at those instead.
  38. //
  39. // For each trace, we compute the critical path length, which is the number of
  40. // cycles required to execute the trace when execution is limited by data
  41. // dependencies only. We also compute the resource height, which is the number
  42. // of cycles required to execute all instructions in the trace when ignoring
  43. // data dependencies.
  44. //
  45. // Every instruction in the current block has a slack - the number of cycles
  46. // execution of the instruction can be delayed without extending the critical
  47. // path.
  48. //
  49. //===----------------------------------------------------------------------===//
  50. #ifndef LLVM_CODEGEN_MACHINETRACEMETRICS_H
  51. #define LLVM_CODEGEN_MACHINETRACEMETRICS_H
  52. #include "llvm/ADT/SparseSet.h"
  53. #include "llvm/ADT/ArrayRef.h"
  54. #include "llvm/ADT/DenseMap.h"
  55. #include "llvm/ADT/SmallVector.h"
  56. #include "llvm/CodeGen/MachineBasicBlock.h"
  57. #include "llvm/CodeGen/MachineFunctionPass.h"
  58. #include "llvm/CodeGen/TargetSchedule.h"
  59. namespace llvm {
  60. class AnalysisUsage;
  61. class MachineFunction;
  62. class MachineInstr;
  63. class MachineLoop;
  64. class MachineLoopInfo;
  65. class MachineRegisterInfo;
  66. struct MCSchedClassDesc;
  67. class raw_ostream;
  68. class TargetInstrInfo;
  69. class TargetRegisterInfo;
  70. // Keep track of physreg data dependencies by recording each live register unit.
  71. // Associate each regunit with an instruction operand. Depending on the
  72. // direction instructions are scanned, it could be the operand that defined the
  73. // regunit, or the highest operand to read the regunit.
  74. struct LiveRegUnit {
  75. unsigned RegUnit;
  76. unsigned Cycle = 0;
  77. const MachineInstr *MI = nullptr;
  78. unsigned Op = 0;
  79. unsigned getSparseSetIndex() const { return RegUnit; }
  80. LiveRegUnit(unsigned RU) : RegUnit(RU) {}
  81. };
  82. class MachineTraceMetrics : public MachineFunctionPass {
  83. const MachineFunction *MF = nullptr;
  84. const TargetInstrInfo *TII = nullptr;
  85. const TargetRegisterInfo *TRI = nullptr;
  86. const MachineRegisterInfo *MRI = nullptr;
  87. const MachineLoopInfo *Loops = nullptr;
  88. TargetSchedModel SchedModel;
  89. public:
  90. friend class Ensemble;
  91. friend class Trace;
  92. class Ensemble;
  93. static char ID;
  94. MachineTraceMetrics();
  95. void getAnalysisUsage(AnalysisUsage&) const override;
  96. bool runOnMachineFunction(MachineFunction&) override;
  97. void releaseMemory() override;
  98. void verifyAnalysis() const override;
  99. /// Per-basic block information that doesn't depend on the trace through the
  100. /// block.
  101. struct FixedBlockInfo {
  102. /// The number of non-trivial instructions in the block.
  103. /// Doesn't count PHI and COPY instructions that are likely to be removed.
  104. unsigned InstrCount = ~0u;
  105. /// True when the block contains calls.
  106. bool HasCalls = false;
  107. FixedBlockInfo() = default;
  108. /// Returns true when resource information for this block has been computed.
  109. bool hasResources() const { return InstrCount != ~0u; }
  110. /// Invalidate resource information.
  111. void invalidate() { InstrCount = ~0u; }
  112. };
  113. /// Get the fixed resource information about MBB. Compute it on demand.
  114. const FixedBlockInfo *getResources(const MachineBasicBlock*);
  115. /// Get the scaled number of cycles used per processor resource in MBB.
  116. /// This is an array with SchedModel.getNumProcResourceKinds() entries.
  117. /// The getResources() function above must have been called first.
  118. ///
  119. /// These numbers have already been scaled by SchedModel.getResourceFactor().
  120. ArrayRef<unsigned> getProcResourceCycles(unsigned MBBNum) const;
  121. /// A virtual register or regunit required by a basic block or its trace
  122. /// successors.
  123. struct LiveInReg {
  124. /// The virtual register required, or a register unit.
  125. Register Reg;
  126. /// For virtual registers: Minimum height of the defining instruction.
  127. /// For regunits: Height of the highest user in the trace.
  128. unsigned Height;
  129. LiveInReg(Register Reg, unsigned Height = 0) : Reg(Reg), Height(Height) {}
  130. };
  131. /// Per-basic block information that relates to a specific trace through the
  132. /// block. Convergent traces means that only one of these is required per
  133. /// block in a trace ensemble.
  134. struct TraceBlockInfo {
  135. /// Trace predecessor, or NULL for the first block in the trace.
  136. /// Valid when hasValidDepth().
  137. const MachineBasicBlock *Pred = nullptr;
  138. /// Trace successor, or NULL for the last block in the trace.
  139. /// Valid when hasValidHeight().
  140. const MachineBasicBlock *Succ = nullptr;
  141. /// The block number of the head of the trace. (When hasValidDepth()).
  142. unsigned Head;
  143. /// The block number of the tail of the trace. (When hasValidHeight()).
  144. unsigned Tail;
  145. /// Accumulated number of instructions in the trace above this block.
  146. /// Does not include instructions in this block.
  147. unsigned InstrDepth = ~0u;
  148. /// Accumulated number of instructions in the trace below this block.
  149. /// Includes instructions in this block.
  150. unsigned InstrHeight = ~0u;
  151. TraceBlockInfo() = default;
  152. /// Returns true if the depth resources have been computed from the trace
  153. /// above this block.
  154. bool hasValidDepth() const { return InstrDepth != ~0u; }
  155. /// Returns true if the height resources have been computed from the trace
  156. /// below this block.
  157. bool hasValidHeight() const { return InstrHeight != ~0u; }
  158. /// Invalidate depth resources when some block above this one has changed.
  159. void invalidateDepth() { InstrDepth = ~0u; HasValidInstrDepths = false; }
  160. /// Invalidate height resources when a block below this one has changed.
  161. void invalidateHeight() { InstrHeight = ~0u; HasValidInstrHeights = false; }
  162. /// Assuming that this is a dominator of TBI, determine if it contains
  163. /// useful instruction depths. A dominating block can be above the current
  164. /// trace head, and any dependencies from such a far away dominator are not
  165. /// expected to affect the critical path.
  166. ///
  167. /// Also returns true when TBI == this.
  168. bool isUsefulDominator(const TraceBlockInfo &TBI) const {
  169. // The trace for TBI may not even be calculated yet.
  170. if (!hasValidDepth() || !TBI.hasValidDepth())
  171. return false;
  172. // Instruction depths are only comparable if the traces share a head.
  173. if (Head != TBI.Head)
  174. return false;
  175. // It is almost always the case that TBI belongs to the same trace as
  176. // this block, but rare convoluted cases involving irreducible control
  177. // flow, a dominator may share a trace head without actually being on the
  178. // same trace as TBI. This is not a big problem as long as it doesn't
  179. // increase the instruction depth.
  180. return HasValidInstrDepths && InstrDepth <= TBI.InstrDepth;
  181. }
  182. // Data-dependency-related information. Per-instruction depth and height
  183. // are computed from data dependencies in the current trace, using
  184. // itinerary data.
  185. /// Instruction depths have been computed. This implies hasValidDepth().
  186. bool HasValidInstrDepths = false;
  187. /// Instruction heights have been computed. This implies hasValidHeight().
  188. bool HasValidInstrHeights = false;
  189. /// Critical path length. This is the number of cycles in the longest data
  190. /// dependency chain through the trace. This is only valid when both
  191. /// HasValidInstrDepths and HasValidInstrHeights are set.
  192. unsigned CriticalPath;
  193. /// Live-in registers. These registers are defined above the current block
  194. /// and used by this block or a block below it.
  195. /// This does not include PHI uses in the current block, but it does
  196. /// include PHI uses in deeper blocks.
  197. SmallVector<LiveInReg, 4> LiveIns;
  198. void print(raw_ostream&) const;
  199. };
  200. /// InstrCycles represents the cycle height and depth of an instruction in a
  201. /// trace.
  202. struct InstrCycles {
  203. /// Earliest issue cycle as determined by data dependencies and instruction
  204. /// latencies from the beginning of the trace. Data dependencies from
  205. /// before the trace are not included.
  206. unsigned Depth;
  207. /// Minimum number of cycles from this instruction is issued to the of the
  208. /// trace, as determined by data dependencies and instruction latencies.
  209. unsigned Height;
  210. };
  211. /// A trace represents a plausible sequence of executed basic blocks that
  212. /// passes through the current basic block one. The Trace class serves as a
  213. /// handle to internal cached data structures.
  214. class Trace {
  215. Ensemble &TE;
  216. TraceBlockInfo &TBI;
  217. unsigned getBlockNum() const { return &TBI - &TE.BlockInfo[0]; }
  218. public:
  219. explicit Trace(Ensemble &te, TraceBlockInfo &tbi) : TE(te), TBI(tbi) {}
  220. void print(raw_ostream&) const;
  221. /// Compute the total number of instructions in the trace.
  222. unsigned getInstrCount() const {
  223. return TBI.InstrDepth + TBI.InstrHeight;
  224. }
  225. /// Return the resource depth of the top/bottom of the trace center block.
  226. /// This is the number of cycles required to execute all instructions from
  227. /// the trace head to the trace center block. The resource depth only
  228. /// considers execution resources, it ignores data dependencies.
  229. /// When Bottom is set, instructions in the trace center block are included.
  230. unsigned getResourceDepth(bool Bottom) const;
  231. /// Return the resource length of the trace. This is the number of cycles
  232. /// required to execute the instructions in the trace if they were all
  233. /// independent, exposing the maximum instruction-level parallelism.
  234. ///
  235. /// Any blocks in Extrablocks are included as if they were part of the
  236. /// trace. Likewise, extra resources required by the specified scheduling
  237. /// classes are included. For the caller to account for extra machine
  238. /// instructions, it must first resolve each instruction's scheduling class.
  239. unsigned getResourceLength(
  240. ArrayRef<const MachineBasicBlock *> Extrablocks = std::nullopt,
  241. ArrayRef<const MCSchedClassDesc *> ExtraInstrs = std::nullopt,
  242. ArrayRef<const MCSchedClassDesc *> RemoveInstrs = std::nullopt) const;
  243. /// Return the length of the (data dependency) critical path through the
  244. /// trace.
  245. unsigned getCriticalPath() const { return TBI.CriticalPath; }
  246. /// Return the depth and height of MI. The depth is only valid for
  247. /// instructions in or above the trace center block. The height is only
  248. /// valid for instructions in or below the trace center block.
  249. InstrCycles getInstrCycles(const MachineInstr &MI) const {
  250. return TE.Cycles.lookup(&MI);
  251. }
  252. /// Return the slack of MI. This is the number of cycles MI can be delayed
  253. /// before the critical path becomes longer.
  254. /// MI must be an instruction in the trace center block.
  255. unsigned getInstrSlack(const MachineInstr &MI) const;
  256. /// Return the Depth of a PHI instruction in a trace center block successor.
  257. /// The PHI does not have to be part of the trace.
  258. unsigned getPHIDepth(const MachineInstr &PHI) const;
  259. /// A dependence is useful if the basic block of the defining instruction
  260. /// is part of the trace of the user instruction. It is assumed that DefMI
  261. /// dominates UseMI (see also isUsefulDominator).
  262. bool isDepInTrace(const MachineInstr &DefMI,
  263. const MachineInstr &UseMI) const;
  264. };
  265. /// A trace ensemble is a collection of traces selected using the same
  266. /// strategy, for example 'minimum resource height'. There is one trace for
  267. /// every block in the function.
  268. class Ensemble {
  269. friend class Trace;
  270. SmallVector<TraceBlockInfo, 4> BlockInfo;
  271. DenseMap<const MachineInstr*, InstrCycles> Cycles;
  272. SmallVector<unsigned, 0> ProcResourceDepths;
  273. SmallVector<unsigned, 0> ProcResourceHeights;
  274. void computeTrace(const MachineBasicBlock*);
  275. void computeDepthResources(const MachineBasicBlock*);
  276. void computeHeightResources(const MachineBasicBlock*);
  277. unsigned computeCrossBlockCriticalPath(const TraceBlockInfo&);
  278. void computeInstrDepths(const MachineBasicBlock*);
  279. void computeInstrHeights(const MachineBasicBlock*);
  280. void addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
  281. ArrayRef<const MachineBasicBlock*> Trace);
  282. protected:
  283. MachineTraceMetrics &MTM;
  284. explicit Ensemble(MachineTraceMetrics*);
  285. virtual const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) =0;
  286. virtual const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) =0;
  287. const MachineLoop *getLoopFor(const MachineBasicBlock*) const;
  288. const TraceBlockInfo *getDepthResources(const MachineBasicBlock*) const;
  289. const TraceBlockInfo *getHeightResources(const MachineBasicBlock*) const;
  290. ArrayRef<unsigned> getProcResourceDepths(unsigned MBBNum) const;
  291. ArrayRef<unsigned> getProcResourceHeights(unsigned MBBNum) const;
  292. public:
  293. virtual ~Ensemble();
  294. virtual const char *getName() const = 0;
  295. void print(raw_ostream&) const;
  296. void invalidate(const MachineBasicBlock *MBB);
  297. void verify() const;
  298. /// Get the trace that passes through MBB.
  299. /// The trace is computed on demand.
  300. Trace getTrace(const MachineBasicBlock *MBB);
  301. /// Updates the depth of an machine instruction, given RegUnits.
  302. void updateDepth(TraceBlockInfo &TBI, const MachineInstr&,
  303. SparseSet<LiveRegUnit> &RegUnits);
  304. void updateDepth(const MachineBasicBlock *, const MachineInstr&,
  305. SparseSet<LiveRegUnit> &RegUnits);
  306. /// Updates the depth of the instructions from Start to End.
  307. void updateDepths(MachineBasicBlock::iterator Start,
  308. MachineBasicBlock::iterator End,
  309. SparseSet<LiveRegUnit> &RegUnits);
  310. };
  311. /// Strategies for selecting traces.
  312. enum Strategy {
  313. /// Select the trace through a block that has the fewest instructions.
  314. TS_MinInstrCount,
  315. TS_NumStrategies
  316. };
  317. /// Get the trace ensemble representing the given trace selection strategy.
  318. /// The returned Ensemble object is owned by the MachineTraceMetrics analysis,
  319. /// and valid for the lifetime of the analysis pass.
  320. Ensemble *getEnsemble(Strategy);
  321. /// Invalidate cached information about MBB. This must be called *before* MBB
  322. /// is erased, or the CFG is otherwise changed.
  323. ///
  324. /// This invalidates per-block information about resource usage for MBB only,
  325. /// and it invalidates per-trace information for any trace that passes
  326. /// through MBB.
  327. ///
  328. /// Call Ensemble::getTrace() again to update any trace handles.
  329. void invalidate(const MachineBasicBlock *MBB);
  330. private:
  331. // One entry per basic block, indexed by block number.
  332. SmallVector<FixedBlockInfo, 4> BlockInfo;
  333. // Cycles consumed on each processor resource per block.
  334. // The number of processor resource kinds is constant for a given subtarget,
  335. // but it is not known at compile time. The number of cycles consumed by
  336. // block B on processor resource R is at ProcResourceCycles[B*Kinds + R]
  337. // where Kinds = SchedModel.getNumProcResourceKinds().
  338. SmallVector<unsigned, 0> ProcResourceCycles;
  339. // One ensemble per strategy.
  340. Ensemble* Ensembles[TS_NumStrategies];
  341. // Convert scaled resource usage to a cycle count that can be compared with
  342. // latencies.
  343. unsigned getCycles(unsigned Scaled) {
  344. unsigned Factor = SchedModel.getLatencyFactor();
  345. return (Scaled + Factor - 1) / Factor;
  346. }
  347. };
  348. inline raw_ostream &operator<<(raw_ostream &OS,
  349. const MachineTraceMetrics::Trace &Tr) {
  350. Tr.print(OS);
  351. return OS;
  352. }
  353. inline raw_ostream &operator<<(raw_ostream &OS,
  354. const MachineTraceMetrics::Ensemble &En) {
  355. En.print(OS);
  356. return OS;
  357. }
  358. } // end namespace llvm
  359. #endif // LLVM_CODEGEN_MACHINETRACEMETRICS_H
  360. #ifdef __GNUC__
  361. #pragma GCC diagnostic pop
  362. #endif