LLVM API Documentation
00001 //===- lib/CodeGen/MachineTraceMetrics.h - Super-scalar metrics -*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the interface for the MachineTraceMetrics analysis pass 00011 // that estimates CPU resource usage and critical data dependency paths through 00012 // preferred traces. This is useful for super-scalar CPUs where execution speed 00013 // can be limited both by data dependencies and by limited execution resources. 00014 // 00015 // Out-of-order CPUs will often be executing instructions from multiple basic 00016 // blocks at the same time. This makes it difficult to estimate the resource 00017 // usage accurately in a single basic block. Resources can be estimated better 00018 // by looking at a trace through the current basic block. 00019 // 00020 // For every block, the MachineTraceMetrics pass will pick a preferred trace 00021 // that passes through the block. The trace is chosen based on loop structure, 00022 // branch probabilities, and resource usage. The intention is to pick likely 00023 // traces that would be the most affected by code transformations. 00024 // 00025 // It is expensive to compute a full arbitrary trace for every block, so to 00026 // save some computations, traces are chosen to be convergent. This means that 00027 // if the traces through basic blocks A and B ever cross when moving away from 00028 // A and B, they never diverge again. This applies in both directions - If the 00029 // traces meet above A and B, they won't diverge when going further back. 00030 // 00031 // Traces tend to align with loops. The trace through a block in an inner loop 00032 // will begin at the loop entry block and end at a back edge. If there are 00033 // nested loops, the trace may begin and end at those instead. 00034 // 00035 // For each trace, we compute the critical path length, which is the number of 00036 // cycles required to execute the trace when execution is limited by data 00037 // dependencies only. We also compute the resource height, which is the number 00038 // of cycles required to execute all instructions in the trace when ignoring 00039 // data dependencies. 00040 // 00041 // Every instruction in the current block has a slack - the number of cycles 00042 // execution of the instruction can be delayed without extending the critical 00043 // path. 00044 // 00045 //===----------------------------------------------------------------------===// 00046 00047 #ifndef LLVM_CODEGEN_MACHINETRACEMETRICS_H 00048 #define LLVM_CODEGEN_MACHINETRACEMETRICS_H 00049 00050 #include "llvm/ADT/ArrayRef.h" 00051 #include "llvm/ADT/DenseMap.h" 00052 #include "llvm/CodeGen/MachineFunctionPass.h" 00053 #include "llvm/CodeGen/TargetSchedule.h" 00054 00055 namespace llvm { 00056 00057 class InstrItineraryData; 00058 class MachineBasicBlock; 00059 class MachineInstr; 00060 class MachineLoop; 00061 class MachineLoopInfo; 00062 class MachineRegisterInfo; 00063 class TargetInstrInfo; 00064 class TargetRegisterInfo; 00065 class raw_ostream; 00066 00067 class MachineTraceMetrics : public MachineFunctionPass { 00068 const MachineFunction *MF; 00069 const TargetInstrInfo *TII; 00070 const TargetRegisterInfo *TRI; 00071 const MachineRegisterInfo *MRI; 00072 const MachineLoopInfo *Loops; 00073 TargetSchedModel SchedModel; 00074 00075 public: 00076 class Ensemble; 00077 class Trace; 00078 static char ID; 00079 MachineTraceMetrics(); 00080 void getAnalysisUsage(AnalysisUsage&) const override; 00081 bool runOnMachineFunction(MachineFunction&) override; 00082 void releaseMemory() override; 00083 void verifyAnalysis() const override; 00084 00085 friend class Ensemble; 00086 friend class Trace; 00087 00088 /// Per-basic block information that doesn't depend on the trace through the 00089 /// block. 00090 struct FixedBlockInfo { 00091 /// The number of non-trivial instructions in the block. 00092 /// Doesn't count PHI and COPY instructions that are likely to be removed. 00093 unsigned InstrCount; 00094 00095 /// True when the block contains calls. 00096 bool HasCalls; 00097 00098 FixedBlockInfo() : InstrCount(~0u), HasCalls(false) {} 00099 00100 /// Returns true when resource information for this block has been computed. 00101 bool hasResources() const { return InstrCount != ~0u; } 00102 00103 /// Invalidate resource information. 00104 void invalidate() { InstrCount = ~0u; } 00105 }; 00106 00107 /// Get the fixed resource information about MBB. Compute it on demand. 00108 const FixedBlockInfo *getResources(const MachineBasicBlock*); 00109 00110 /// Get the scaled number of cycles used per processor resource in MBB. 00111 /// This is an array with SchedModel.getNumProcResourceKinds() entries. 00112 /// The getResources() function above must have been called first. 00113 /// 00114 /// These numbers have already been scaled by SchedModel.getResourceFactor(). 00115 ArrayRef<unsigned> getProcResourceCycles(unsigned MBBNum) const; 00116 00117 /// A virtual register or regunit required by a basic block or its trace 00118 /// successors. 00119 struct LiveInReg { 00120 /// The virtual register required, or a register unit. 00121 unsigned Reg; 00122 00123 /// For virtual registers: Minimum height of the defining instruction. 00124 /// For regunits: Height of the highest user in the trace. 00125 unsigned Height; 00126 00127 LiveInReg(unsigned Reg, unsigned Height = 0) : Reg(Reg), Height(Height) {} 00128 }; 00129 00130 /// Per-basic block information that relates to a specific trace through the 00131 /// block. Convergent traces means that only one of these is required per 00132 /// block in a trace ensemble. 00133 struct TraceBlockInfo { 00134 /// Trace predecessor, or NULL for the first block in the trace. 00135 /// Valid when hasValidDepth(). 00136 const MachineBasicBlock *Pred; 00137 00138 /// Trace successor, or NULL for the last block in the trace. 00139 /// Valid when hasValidHeight(). 00140 const MachineBasicBlock *Succ; 00141 00142 /// The block number of the head of the trace. (When hasValidDepth()). 00143 unsigned Head; 00144 00145 /// The block number of the tail of the trace. (When hasValidHeight()). 00146 unsigned Tail; 00147 00148 /// Accumulated number of instructions in the trace above this block. 00149 /// Does not include instructions in this block. 00150 unsigned InstrDepth; 00151 00152 /// Accumulated number of instructions in the trace below this block. 00153 /// Includes instructions in this block. 00154 unsigned InstrHeight; 00155 00156 TraceBlockInfo() : 00157 Pred(nullptr), Succ(nullptr), 00158 InstrDepth(~0u), InstrHeight(~0u), 00159 HasValidInstrDepths(false), HasValidInstrHeights(false) {} 00160 00161 /// Returns true if the depth resources have been computed from the trace 00162 /// above this block. 00163 bool hasValidDepth() const { return InstrDepth != ~0u; } 00164 00165 /// Returns true if the height resources have been computed from the trace 00166 /// below this block. 00167 bool hasValidHeight() const { return InstrHeight != ~0u; } 00168 00169 /// Invalidate depth resources when some block above this one has changed. 00170 void invalidateDepth() { InstrDepth = ~0u; HasValidInstrDepths = false; } 00171 00172 /// Invalidate height resources when a block below this one has changed. 00173 void invalidateHeight() { InstrHeight = ~0u; HasValidInstrHeights = false; } 00174 00175 /// Assuming that this is a dominator of TBI, determine if it contains 00176 /// useful instruction depths. A dominating block can be above the current 00177 /// trace head, and any dependencies from such a far away dominator are not 00178 /// expected to affect the critical path. 00179 /// 00180 /// Also returns true when TBI == this. 00181 bool isUsefulDominator(const TraceBlockInfo &TBI) const { 00182 // The trace for TBI may not even be calculated yet. 00183 if (!hasValidDepth() || !TBI.hasValidDepth()) 00184 return false; 00185 // Instruction depths are only comparable if the traces share a head. 00186 if (Head != TBI.Head) 00187 return false; 00188 // It is almost always the case that TBI belongs to the same trace as 00189 // this block, but rare convoluted cases involving irreducible control 00190 // flow, a dominator may share a trace head without actually being on the 00191 // same trace as TBI. This is not a big problem as long as it doesn't 00192 // increase the instruction depth. 00193 return HasValidInstrDepths && InstrDepth <= TBI.InstrDepth; 00194 } 00195 00196 // Data-dependency-related information. Per-instruction depth and height 00197 // are computed from data dependencies in the current trace, using 00198 // itinerary data. 00199 00200 /// Instruction depths have been computed. This implies hasValidDepth(). 00201 bool HasValidInstrDepths; 00202 00203 /// Instruction heights have been computed. This implies hasValidHeight(). 00204 bool HasValidInstrHeights; 00205 00206 /// Critical path length. This is the number of cycles in the longest data 00207 /// dependency chain through the trace. This is only valid when both 00208 /// HasValidInstrDepths and HasValidInstrHeights are set. 00209 unsigned CriticalPath; 00210 00211 /// Live-in registers. These registers are defined above the current block 00212 /// and used by this block or a block below it. 00213 /// This does not include PHI uses in the current block, but it does 00214 /// include PHI uses in deeper blocks. 00215 SmallVector<LiveInReg, 4> LiveIns; 00216 00217 void print(raw_ostream&) const; 00218 }; 00219 00220 /// InstrCycles represents the cycle height and depth of an instruction in a 00221 /// trace. 00222 struct InstrCycles { 00223 /// Earliest issue cycle as determined by data dependencies and instruction 00224 /// latencies from the beginning of the trace. Data dependencies from 00225 /// before the trace are not included. 00226 unsigned Depth; 00227 00228 /// Minimum number of cycles from this instruction is issued to the of the 00229 /// trace, as determined by data dependencies and instruction latencies. 00230 unsigned Height; 00231 }; 00232 00233 /// A trace represents a plausible sequence of executed basic blocks that 00234 /// passes through the current basic block one. The Trace class serves as a 00235 /// handle to internal cached data structures. 00236 class Trace { 00237 Ensemble &TE; 00238 TraceBlockInfo &TBI; 00239 00240 unsigned getBlockNum() const { return &TBI - &TE.BlockInfo[0]; } 00241 00242 public: 00243 explicit Trace(Ensemble &te, TraceBlockInfo &tbi) : TE(te), TBI(tbi) {} 00244 void print(raw_ostream&) const; 00245 00246 /// Compute the total number of instructions in the trace. 00247 unsigned getInstrCount() const { 00248 return TBI.InstrDepth + TBI.InstrHeight; 00249 } 00250 00251 /// Return the resource depth of the top/bottom of the trace center block. 00252 /// This is the number of cycles required to execute all instructions from 00253 /// the trace head to the trace center block. The resource depth only 00254 /// considers execution resources, it ignores data dependencies. 00255 /// When Bottom is set, instructions in the trace center block are included. 00256 unsigned getResourceDepth(bool Bottom) const; 00257 00258 /// Return the resource length of the trace. This is the number of cycles 00259 /// required to execute the instructions in the trace if they were all 00260 /// independent, exposing the maximum instruction-level parallelism. 00261 /// 00262 /// Any blocks in Extrablocks are included as if they were part of the 00263 /// trace. Likewise, extra resources required by the specified scheduling 00264 /// classes are included. For the caller to account for extra machine 00265 /// instructions, it must first resolve each instruction's scheduling class. 00266 unsigned getResourceLength( 00267 ArrayRef<const MachineBasicBlock *> Extrablocks = None, 00268 ArrayRef<const MCSchedClassDesc *> ExtraInstrs = None, 00269 ArrayRef<const MCSchedClassDesc *> RemoveInstrs = None) const; 00270 00271 /// Return the length of the (data dependency) critical path through the 00272 /// trace. 00273 unsigned getCriticalPath() const { return TBI.CriticalPath; } 00274 00275 /// Return the depth and height of MI. The depth is only valid for 00276 /// instructions in or above the trace center block. The height is only 00277 /// valid for instructions in or below the trace center block. 00278 InstrCycles getInstrCycles(const MachineInstr *MI) const { 00279 return TE.Cycles.lookup(MI); 00280 } 00281 00282 /// Return the slack of MI. This is the number of cycles MI can be delayed 00283 /// before the critical path becomes longer. 00284 /// MI must be an instruction in the trace center block. 00285 unsigned getInstrSlack(const MachineInstr *MI) const; 00286 00287 /// Return the Depth of a PHI instruction in a trace center block successor. 00288 /// The PHI does not have to be part of the trace. 00289 unsigned getPHIDepth(const MachineInstr *PHI) const; 00290 00291 /// A dependence is useful if the basic block of the defining instruction 00292 /// is part of the trace of the user instruction. It is assumed that DefMI 00293 /// dominates UseMI (see also isUsefulDominator). 00294 bool isDepInTrace(const MachineInstr *DefMI, 00295 const MachineInstr *UseMI) const; 00296 }; 00297 00298 /// A trace ensemble is a collection of traces selected using the same 00299 /// strategy, for example 'minimum resource height'. There is one trace for 00300 /// every block in the function. 00301 class Ensemble { 00302 SmallVector<TraceBlockInfo, 4> BlockInfo; 00303 DenseMap<const MachineInstr*, InstrCycles> Cycles; 00304 SmallVector<unsigned, 0> ProcResourceDepths; 00305 SmallVector<unsigned, 0> ProcResourceHeights; 00306 friend class Trace; 00307 00308 void computeTrace(const MachineBasicBlock*); 00309 void computeDepthResources(const MachineBasicBlock*); 00310 void computeHeightResources(const MachineBasicBlock*); 00311 unsigned computeCrossBlockCriticalPath(const TraceBlockInfo&); 00312 void computeInstrDepths(const MachineBasicBlock*); 00313 void computeInstrHeights(const MachineBasicBlock*); 00314 void addLiveIns(const MachineInstr *DefMI, unsigned DefOp, 00315 ArrayRef<const MachineBasicBlock*> Trace); 00316 00317 protected: 00318 MachineTraceMetrics &MTM; 00319 virtual const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) =0; 00320 virtual const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) =0; 00321 explicit Ensemble(MachineTraceMetrics*); 00322 const MachineLoop *getLoopFor(const MachineBasicBlock*) const; 00323 const TraceBlockInfo *getDepthResources(const MachineBasicBlock*) const; 00324 const TraceBlockInfo *getHeightResources(const MachineBasicBlock*) const; 00325 ArrayRef<unsigned> getProcResourceDepths(unsigned MBBNum) const; 00326 ArrayRef<unsigned> getProcResourceHeights(unsigned MBBNum) const; 00327 00328 public: 00329 virtual ~Ensemble(); 00330 virtual const char *getName() const =0; 00331 void print(raw_ostream&) const; 00332 void invalidate(const MachineBasicBlock *MBB); 00333 void verify() const; 00334 00335 /// Get the trace that passes through MBB. 00336 /// The trace is computed on demand. 00337 Trace getTrace(const MachineBasicBlock *MBB); 00338 }; 00339 00340 /// Strategies for selecting traces. 00341 enum Strategy { 00342 /// Select the trace through a block that has the fewest instructions. 00343 TS_MinInstrCount, 00344 00345 TS_NumStrategies 00346 }; 00347 00348 /// Get the trace ensemble representing the given trace selection strategy. 00349 /// The returned Ensemble object is owned by the MachineTraceMetrics analysis, 00350 /// and valid for the lifetime of the analysis pass. 00351 Ensemble *getEnsemble(Strategy); 00352 00353 /// Invalidate cached information about MBB. This must be called *before* MBB 00354 /// is erased, or the CFG is otherwise changed. 00355 /// 00356 /// This invalidates per-block information about resource usage for MBB only, 00357 /// and it invalidates per-trace information for any trace that passes 00358 /// through MBB. 00359 /// 00360 /// Call Ensemble::getTrace() again to update any trace handles. 00361 void invalidate(const MachineBasicBlock *MBB); 00362 00363 private: 00364 // One entry per basic block, indexed by block number. 00365 SmallVector<FixedBlockInfo, 4> BlockInfo; 00366 00367 // Cycles consumed on each processor resource per block. 00368 // The number of processor resource kinds is constant for a given subtarget, 00369 // but it is not known at compile time. The number of cycles consumed by 00370 // block B on processor resource R is at ProcResourceCycles[B*Kinds + R] 00371 // where Kinds = SchedModel.getNumProcResourceKinds(). 00372 SmallVector<unsigned, 0> ProcResourceCycles; 00373 00374 // One ensemble per strategy. 00375 Ensemble* Ensembles[TS_NumStrategies]; 00376 00377 // Convert scaled resource usage to a cycle count that can be compared with 00378 // latencies. 00379 unsigned getCycles(unsigned Scaled) { 00380 unsigned Factor = SchedModel.getLatencyFactor(); 00381 return (Scaled + Factor - 1) / Factor; 00382 } 00383 }; 00384 00385 inline raw_ostream &operator<<(raw_ostream &OS, 00386 const MachineTraceMetrics::Trace &Tr) { 00387 Tr.print(OS); 00388 return OS; 00389 } 00390 00391 inline raw_ostream &operator<<(raw_ostream &OS, 00392 const MachineTraceMetrics::Ensemble &En) { 00393 En.print(OS); 00394 return OS; 00395 } 00396 } // end namespace llvm 00397 00398 #endif