Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:32

0001 //===- lib/CodeGen/MachineTraceMetrics.h - Super-scalar metrics -*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file defines the interface for the MachineTraceMetrics analysis pass
0010 // that estimates CPU resource usage and critical data dependency paths through
0011 // preferred traces. This is useful for super-scalar CPUs where execution speed
0012 // can be limited both by data dependencies and by limited execution resources.
0013 //
0014 // Out-of-order CPUs will often be executing instructions from multiple basic
0015 // blocks at the same time. This makes it difficult to estimate the resource
0016 // usage accurately in a single basic block. Resources can be estimated better
0017 // by looking at a trace through the current basic block.
0018 //
0019 // For every block, the MachineTraceMetrics pass will pick a preferred trace
0020 // that passes through the block. The trace is chosen based on loop structure,
0021 // branch probabilities, and resource usage. The intention is to pick likely
0022 // traces that would be the most affected by code transformations.
0023 //
0024 // It is expensive to compute a full arbitrary trace for every block, so to
0025 // save some computations, traces are chosen to be convergent. This means that
0026 // if the traces through basic blocks A and B ever cross when moving away from
0027 // A and B, they never diverge again. This applies in both directions - If the
0028 // traces meet above A and B, they won't diverge when going further back.
0029 //
0030 // Traces tend to align with loops. The trace through a block in an inner loop
0031 // will begin at the loop entry block and end at a back edge. If there are
0032 // nested loops, the trace may begin and end at those instead.
0033 //
0034 // For each trace, we compute the critical path length, which is the number of
0035 // cycles required to execute the trace when execution is limited by data
0036 // dependencies only. We also compute the resource height, which is the number
0037 // of cycles required to execute all instructions in the trace when ignoring
0038 // data dependencies.
0039 //
0040 // Every instruction in the current block has a slack - the number of cycles
0041 // execution of the instruction can be delayed without extending the critical
0042 // path.
0043 //
0044 //===----------------------------------------------------------------------===//
0045 
0046 #ifndef LLVM_CODEGEN_MACHINETRACEMETRICS_H
0047 #define LLVM_CODEGEN_MACHINETRACEMETRICS_H
0048 
0049 #include "llvm/ADT/ArrayRef.h"
0050 #include "llvm/ADT/DenseMap.h"
0051 #include "llvm/ADT/SmallVector.h"
0052 #include "llvm/ADT/SparseSet.h"
0053 #include "llvm/CodeGen/MachineBasicBlock.h"
0054 #include "llvm/CodeGen/MachineFunctionPass.h"
0055 #include "llvm/CodeGen/MachinePassManager.h"
0056 #include "llvm/CodeGen/TargetSchedule.h"
0057 
0058 namespace llvm {
0059 
0060 class AnalysisUsage;
0061 class MachineFunction;
0062 class MachineInstr;
0063 class MachineLoop;
0064 class MachineLoopInfo;
0065 class MachineRegisterInfo;
0066 struct MCSchedClassDesc;
0067 class raw_ostream;
0068 class TargetInstrInfo;
0069 class TargetRegisterInfo;
0070 
0071 // Keep track of physreg data dependencies by recording each live register unit.
0072 // Associate each regunit with an instruction operand. Depending on the
0073 // direction instructions are scanned, it could be the operand that defined the
0074 // regunit, or the highest operand to read the regunit.
0075 struct LiveRegUnit {
0076   unsigned RegUnit;
0077   unsigned Cycle = 0;
0078   const MachineInstr *MI = nullptr;
0079   unsigned Op = 0;
0080 
0081   unsigned getSparseSetIndex() const { return RegUnit; }
0082 
0083   LiveRegUnit(unsigned RU) : RegUnit(RU) {}
0084 };
0085 
0086 /// Strategies for selecting traces.
0087 enum class MachineTraceStrategy {
0088   /// Select the trace through a block that has the fewest instructions.
0089   TS_MinInstrCount,
0090   /// Select the trace that contains only the current basic block. For instance,
0091   /// this strategy can be used by MachineCombiner to make better decisions when
0092   /// we estimate critical path for in-order cores.
0093   TS_Local,
0094   TS_NumStrategies
0095 };
0096 
0097 class MachineTraceMetrics {
0098   const MachineFunction *MF = nullptr;
0099   const TargetInstrInfo *TII = nullptr;
0100   const TargetRegisterInfo *TRI = nullptr;
0101   const MachineRegisterInfo *MRI = nullptr;
0102   const MachineLoopInfo *Loops = nullptr;
0103   TargetSchedModel SchedModel;
0104 
0105 public:
0106   friend class MachineTraceMetricsWrapperPass;
0107   friend class Ensemble;
0108   friend class Trace;
0109 
0110   class Ensemble;
0111 
0112   // For legacy pass.
0113   MachineTraceMetrics() = default;
0114 
0115   explicit MachineTraceMetrics(MachineFunction &MF, const MachineLoopInfo &LI) {
0116     init(MF, LI);
0117   }
0118 
0119   MachineTraceMetrics(MachineTraceMetrics &&) = default;
0120 
0121   ~MachineTraceMetrics();
0122 
0123   void init(MachineFunction &Func, const MachineLoopInfo &LI);
0124   void clear();
0125 
0126   /// Per-basic block information that doesn't depend on the trace through the
0127   /// block.
0128   struct FixedBlockInfo {
0129     /// The number of non-trivial instructions in the block.
0130     /// Doesn't count PHI and COPY instructions that are likely to be removed.
0131     unsigned InstrCount = ~0u;
0132 
0133     /// True when the block contains calls.
0134     bool HasCalls = false;
0135 
0136     FixedBlockInfo() = default;
0137 
0138     /// Returns true when resource information for this block has been computed.
0139     bool hasResources() const { return InstrCount != ~0u; }
0140 
0141     /// Invalidate resource information.
0142     void invalidate() { InstrCount = ~0u; }
0143   };
0144 
0145   /// Get the fixed resource information about MBB. Compute it on demand.
0146   const FixedBlockInfo *getResources(const MachineBasicBlock*);
0147 
0148   /// Get the scaled number of cycles used per processor resource in MBB.
0149   /// This is an array with SchedModel.getNumProcResourceKinds() entries.
0150   /// The getResources() function above must have been called first.
0151   ///
0152   /// These numbers have already been scaled by SchedModel.getResourceFactor().
0153   ArrayRef<unsigned> getProcReleaseAtCycles(unsigned MBBNum) const;
0154 
0155   /// A virtual register or regunit required by a basic block or its trace
0156   /// successors.
0157   struct LiveInReg {
0158     /// The virtual register required, or a register unit.
0159     Register Reg;
0160 
0161     /// For virtual registers: Minimum height of the defining instruction.
0162     /// For regunits: Height of the highest user in the trace.
0163     unsigned Height;
0164 
0165     LiveInReg(Register Reg, unsigned Height = 0) : Reg(Reg), Height(Height) {}
0166   };
0167 
0168   /// Per-basic block information that relates to a specific trace through the
0169   /// block. Convergent traces means that only one of these is required per
0170   /// block in a trace ensemble.
0171   struct TraceBlockInfo {
0172     /// Trace predecessor, or NULL for the first block in the trace.
0173     /// Valid when hasValidDepth().
0174     const MachineBasicBlock *Pred = nullptr;
0175 
0176     /// Trace successor, or NULL for the last block in the trace.
0177     /// Valid when hasValidHeight().
0178     const MachineBasicBlock *Succ = nullptr;
0179 
0180     /// The block number of the head of the trace. (When hasValidDepth()).
0181     unsigned Head;
0182 
0183     /// The block number of the tail of the trace. (When hasValidHeight()).
0184     unsigned Tail;
0185 
0186     /// Accumulated number of instructions in the trace above this block.
0187     /// Does not include instructions in this block.
0188     unsigned InstrDepth = ~0u;
0189 
0190     /// Accumulated number of instructions in the trace below this block.
0191     /// Includes instructions in this block.
0192     unsigned InstrHeight = ~0u;
0193 
0194     TraceBlockInfo() = default;
0195 
0196     /// Returns true if the depth resources have been computed from the trace
0197     /// above this block.
0198     bool hasValidDepth() const { return InstrDepth != ~0u; }
0199 
0200     /// Returns true if the height resources have been computed from the trace
0201     /// below this block.
0202     bool hasValidHeight() const { return InstrHeight != ~0u; }
0203 
0204     /// Invalidate depth resources when some block above this one has changed.
0205     void invalidateDepth() { InstrDepth = ~0u; HasValidInstrDepths = false; }
0206 
0207     /// Invalidate height resources when a block below this one has changed.
0208     void invalidateHeight() { InstrHeight = ~0u; HasValidInstrHeights = false; }
0209 
0210     /// Assuming that this is a dominator of TBI, determine if it contains
0211     /// useful instruction depths. A dominating block can be above the current
0212     /// trace head, and any dependencies from such a far away dominator are not
0213     /// expected to affect the critical path.
0214     ///
0215     /// Also returns true when TBI == this.
0216     bool isUsefulDominator(const TraceBlockInfo &TBI) const {
0217       // The trace for TBI may not even be calculated yet.
0218       if (!hasValidDepth() || !TBI.hasValidDepth())
0219         return false;
0220       // Instruction depths are only comparable if the traces share a head.
0221       if (Head != TBI.Head)
0222         return false;
0223       // It is almost always the case that TBI belongs to the same trace as
0224       // this block, but rare convoluted cases involving irreducible control
0225       // flow, a dominator may share a trace head without actually being on the
0226       // same trace as TBI. This is not a big problem as long as it doesn't
0227       // increase the instruction depth.
0228       return HasValidInstrDepths && InstrDepth <= TBI.InstrDepth;
0229     }
0230 
0231     // Data-dependency-related information. Per-instruction depth and height
0232     // are computed from data dependencies in the current trace, using
0233     // itinerary data.
0234 
0235     /// Instruction depths have been computed. This implies hasValidDepth().
0236     bool HasValidInstrDepths = false;
0237 
0238     /// Instruction heights have been computed. This implies hasValidHeight().
0239     bool HasValidInstrHeights = false;
0240 
0241     /// Critical path length. This is the number of cycles in the longest data
0242     /// dependency chain through the trace. This is only valid when both
0243     /// HasValidInstrDepths and HasValidInstrHeights are set.
0244     unsigned CriticalPath;
0245 
0246     /// Live-in registers. These registers are defined above the current block
0247     /// and used by this block or a block below it.
0248     /// This does not include PHI uses in the current block, but it does
0249     /// include PHI uses in deeper blocks.
0250     SmallVector<LiveInReg, 4> LiveIns;
0251 
0252     void print(raw_ostream&) const;
0253     void dump() const { print(dbgs()); }
0254   };
0255 
0256   /// InstrCycles represents the cycle height and depth of an instruction in a
0257   /// trace.
0258   struct InstrCycles {
0259     /// Earliest issue cycle as determined by data dependencies and instruction
0260     /// latencies from the beginning of the trace. Data dependencies from
0261     /// before the trace are not included.
0262     unsigned Depth;
0263 
0264     /// Minimum number of cycles from this instruction is issued to the of the
0265     /// trace, as determined by data dependencies and instruction latencies.
0266     unsigned Height;
0267   };
0268 
0269   /// A trace represents a plausible sequence of executed basic blocks that
0270   /// passes through the current basic block one. The Trace class serves as a
0271   /// handle to internal cached data structures.
0272   class Trace {
0273     Ensemble &TE;
0274     TraceBlockInfo &TBI;
0275 
0276     unsigned getBlockNum() const { return &TBI - &TE.BlockInfo[0]; }
0277 
0278   public:
0279     explicit Trace(Ensemble &te, TraceBlockInfo &tbi) : TE(te), TBI(tbi) {}
0280 
0281     void print(raw_ostream&) const;
0282     void dump() const { print(dbgs()); }
0283 
0284     /// Compute the total number of instructions in the trace.
0285     unsigned getInstrCount() const {
0286       return TBI.InstrDepth + TBI.InstrHeight;
0287     }
0288 
0289     /// Return the resource depth of the top/bottom of the trace center block.
0290     /// This is the number of cycles required to execute all instructions from
0291     /// the trace head to the trace center block. The resource depth only
0292     /// considers execution resources, it ignores data dependencies.
0293     /// When Bottom is set, instructions in the trace center block are included.
0294     unsigned getResourceDepth(bool Bottom) const;
0295 
0296     /// Return the resource length of the trace. This is the number of cycles
0297     /// required to execute the instructions in the trace if they were all
0298     /// independent, exposing the maximum instruction-level parallelism.
0299     ///
0300     /// Any blocks in Extrablocks are included as if they were part of the
0301     /// trace. Likewise, extra resources required by the specified scheduling
0302     /// classes are included. For the caller to account for extra machine
0303     /// instructions, it must first resolve each instruction's scheduling class.
0304     unsigned getResourceLength(
0305         ArrayRef<const MachineBasicBlock *> Extrablocks = {},
0306         ArrayRef<const MCSchedClassDesc *> ExtraInstrs = {},
0307         ArrayRef<const MCSchedClassDesc *> RemoveInstrs = {}) const;
0308 
0309     /// Return the length of the (data dependency) critical path through the
0310     /// trace.
0311     unsigned getCriticalPath() const { return TBI.CriticalPath; }
0312 
0313     /// Return the depth and height of MI. The depth is only valid for
0314     /// instructions in or above the trace center block. The height is only
0315     /// valid for instructions in or below the trace center block.
0316     InstrCycles getInstrCycles(const MachineInstr &MI) const {
0317       return TE.Cycles.lookup(&MI);
0318     }
0319 
0320     /// Return the slack of MI. This is the number of cycles MI can be delayed
0321     /// before the critical path becomes longer.
0322     /// MI must be an instruction in the trace center block.
0323     unsigned getInstrSlack(const MachineInstr &MI) const;
0324 
0325     /// Return the Depth of a PHI instruction in a trace center block successor.
0326     /// The PHI does not have to be part of the trace.
0327     unsigned getPHIDepth(const MachineInstr &PHI) const;
0328 
0329     /// A dependence is useful if the basic block of the defining instruction
0330     /// is part of the trace of the user instruction. It is assumed that DefMI
0331     /// dominates UseMI (see also isUsefulDominator).
0332     bool isDepInTrace(const MachineInstr &DefMI,
0333                       const MachineInstr &UseMI) const;
0334   };
0335 
0336   /// A trace ensemble is a collection of traces selected using the same
0337   /// strategy, for example 'minimum resource height'. There is one trace for
0338   /// every block in the function.
0339   class Ensemble {
0340     friend class Trace;
0341 
0342     SmallVector<TraceBlockInfo, 4> BlockInfo;
0343     DenseMap<const MachineInstr*, InstrCycles> Cycles;
0344     SmallVector<unsigned, 0> ProcResourceDepths;
0345     SmallVector<unsigned, 0> ProcResourceHeights;
0346 
0347     void computeTrace(const MachineBasicBlock*);
0348     void computeDepthResources(const MachineBasicBlock*);
0349     void computeHeightResources(const MachineBasicBlock*);
0350     unsigned computeCrossBlockCriticalPath(const TraceBlockInfo&);
0351     void computeInstrDepths(const MachineBasicBlock*);
0352     void computeInstrHeights(const MachineBasicBlock*);
0353     void addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
0354                     ArrayRef<const MachineBasicBlock*> Trace);
0355 
0356   protected:
0357     MachineTraceMetrics &MTM;
0358 
0359     explicit Ensemble(MachineTraceMetrics*);
0360 
0361     virtual const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) =0;
0362     virtual const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) =0;
0363     const MachineLoop *getLoopFor(const MachineBasicBlock*) const;
0364     const TraceBlockInfo *getDepthResources(const MachineBasicBlock*) const;
0365     const TraceBlockInfo *getHeightResources(const MachineBasicBlock*) const;
0366     ArrayRef<unsigned> getProcResourceDepths(unsigned MBBNum) const;
0367     ArrayRef<unsigned> getProcResourceHeights(unsigned MBBNum) const;
0368 
0369   public:
0370     virtual ~Ensemble();
0371 
0372     virtual const char *getName() const = 0;
0373     void print(raw_ostream &) const;
0374     void dump() const { print(dbgs()); }
0375     void invalidate(const MachineBasicBlock *MBB);
0376     void verify() const;
0377 
0378     /// Get the trace that passes through MBB.
0379     /// The trace is computed on demand.
0380     Trace getTrace(const MachineBasicBlock *MBB);
0381 
0382     /// Updates the depth of an machine instruction, given RegUnits.
0383     void updateDepth(TraceBlockInfo &TBI, const MachineInstr&,
0384                      SparseSet<LiveRegUnit> &RegUnits);
0385     void updateDepth(const MachineBasicBlock *, const MachineInstr&,
0386                      SparseSet<LiveRegUnit> &RegUnits);
0387 
0388     /// Updates the depth of the instructions from Start to End.
0389     void updateDepths(MachineBasicBlock::iterator Start,
0390                       MachineBasicBlock::iterator End,
0391                       SparseSet<LiveRegUnit> &RegUnits);
0392 
0393   };
0394 
0395   /// Get the trace ensemble representing the given trace selection strategy.
0396   /// The returned Ensemble object is owned by the MachineTraceMetrics analysis,
0397   /// and valid for the lifetime of the analysis pass.
0398   Ensemble *getEnsemble(MachineTraceStrategy);
0399 
0400   /// Invalidate cached information about MBB. This must be called *before* MBB
0401   /// is erased, or the CFG is otherwise changed.
0402   ///
0403   /// This invalidates per-block information about resource usage for MBB only,
0404   /// and it invalidates per-trace information for any trace that passes
0405   /// through MBB.
0406   ///
0407   /// Call Ensemble::getTrace() again to update any trace handles.
0408   void invalidate(const MachineBasicBlock *MBB);
0409 
0410   /// Handle invalidation explicitly.
0411   bool invalidate(MachineFunction &, const PreservedAnalyses &PA,
0412                   MachineFunctionAnalysisManager::Invalidator &);
0413 
0414   void verifyAnalysis() const;
0415 
0416 private:
0417   // One entry per basic block, indexed by block number.
0418   SmallVector<FixedBlockInfo, 4> BlockInfo;
0419 
0420   // Cycles consumed on each processor resource per block.
0421   // The number of processor resource kinds is constant for a given subtarget,
0422   // but it is not known at compile time. The number of cycles consumed by
0423   // block B on processor resource R is at ProcReleaseAtCycles[B*Kinds + R]
0424   // where Kinds = SchedModel.getNumProcResourceKinds().
0425   SmallVector<unsigned, 0> ProcReleaseAtCycles;
0426 
0427   // One ensemble per strategy.
0428   std::unique_ptr<Ensemble>
0429       Ensembles[static_cast<size_t>(MachineTraceStrategy::TS_NumStrategies)];
0430 
0431   // Convert scaled resource usage to a cycle count that can be compared with
0432   // latencies.
0433   unsigned getCycles(unsigned Scaled) {
0434     unsigned Factor = SchedModel.getLatencyFactor();
0435     return (Scaled + Factor - 1) / Factor;
0436   }
0437 };
0438 
0439 inline raw_ostream &operator<<(raw_ostream &OS,
0440                                const MachineTraceMetrics::Trace &Tr) {
0441   Tr.print(OS);
0442   return OS;
0443 }
0444 
0445 inline raw_ostream &operator<<(raw_ostream &OS,
0446                                const MachineTraceMetrics::Ensemble &En) {
0447   En.print(OS);
0448   return OS;
0449 }
0450 
0451 class MachineTraceMetricsAnalysis
0452     : public AnalysisInfoMixin<MachineTraceMetricsAnalysis> {
0453   friend AnalysisInfoMixin<MachineTraceMetricsAnalysis>;
0454   static AnalysisKey Key;
0455 
0456 public:
0457   using Result = MachineTraceMetrics;
0458   Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM);
0459 };
0460 
0461 /// Verifier pass for \c MachineTraceMetrics.
0462 struct MachineTraceMetricsVerifierPass
0463     : PassInfoMixin<MachineTraceMetricsVerifierPass> {
0464   PreservedAnalyses run(MachineFunction &MF,
0465                         MachineFunctionAnalysisManager &MFAM);
0466   static bool isRequired() { return true; }
0467 };
0468 
0469 class MachineTraceMetricsWrapperPass : public MachineFunctionPass {
0470 public:
0471   static char ID;
0472   MachineTraceMetrics MTM;
0473 
0474   MachineTraceMetricsWrapperPass();
0475 
0476   void getAnalysisUsage(AnalysisUsage &) const override;
0477   bool runOnMachineFunction(MachineFunction &) override;
0478   void releaseMemory() override { MTM.clear(); }
0479   void verifyAnalysis() const override { MTM.verifyAnalysis(); }
0480   MachineTraceMetrics &getMTM() { return MTM; }
0481 };
0482 
0483 } // end namespace llvm
0484 
0485 #endif // LLVM_CODEGEN_MACHINETRACEMETRICS_H