Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

388 lines
15 KiB

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