1 //===- lib/CodeGen/MachineTraceMetrics.cpp ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/CodeGen/MachineTraceMetrics.h"
11 #include "llvm/ADT/PostOrderIterator.h"
12 #include "llvm/ADT/SparseSet.h"
13 #include "llvm/CodeGen/MachineBasicBlock.h"
14 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
15 #include "llvm/CodeGen/MachineLoopInfo.h"
16 #include "llvm/CodeGen/MachineRegisterInfo.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/MC/MCSubtargetInfo.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetSubtargetInfo.h"
28 #define DEBUG_TYPE "machine-trace-metrics"
30 char MachineTraceMetrics::ID = 0;
31 char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
33 INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
34 "machine-trace-metrics", "Machine Trace Metrics", false, true)
35 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
36 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
37 INITIALIZE_PASS_END(MachineTraceMetrics,
38 "machine-trace-metrics", "Machine Trace Metrics", false, true)
40 MachineTraceMetrics::MachineTraceMetrics()
41 : MachineFunctionPass(ID), MF(nullptr), TII(nullptr), TRI(nullptr),
42 MRI(nullptr), Loops(nullptr) {
43 std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
46 void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addRequired<MachineBranchProbabilityInfo>();
49 AU.addRequired<MachineLoopInfo>();
50 MachineFunctionPass::getAnalysisUsage(AU);
53 bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
55 TII = MF->getSubtarget().getInstrInfo();
56 TRI = MF->getSubtarget().getRegisterInfo();
57 MRI = &MF->getRegInfo();
58 Loops = &getAnalysis<MachineLoopInfo>();
59 const TargetSubtargetInfo &ST =
60 MF->getTarget().getSubtarget<TargetSubtargetInfo>();
61 SchedModel.init(ST.getSchedModel(), &ST, TII);
62 BlockInfo.resize(MF->getNumBlockIDs());
63 ProcResourceCycles.resize(MF->getNumBlockIDs() *
64 SchedModel.getNumProcResourceKinds());
68 void MachineTraceMetrics::releaseMemory() {
71 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
73 Ensembles[i] = nullptr;
77 //===----------------------------------------------------------------------===//
78 // Fixed block information
79 //===----------------------------------------------------------------------===//
81 // The number of instructions in a basic block and the CPU resources used by
82 // those instructions don't depend on any given trace strategy.
84 /// Compute the resource usage in basic block MBB.
85 const MachineTraceMetrics::FixedBlockInfo*
86 MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
87 assert(MBB && "No basic block");
88 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
89 if (FBI->hasResources())
92 // Compute resource usage in the block.
93 FBI->HasCalls = false;
94 unsigned InstrCount = 0;
96 // Add up per-processor resource cycles as well.
97 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
98 SmallVector<unsigned, 32> PRCycles(PRKinds);
100 for (const auto &MI : *MBB) {
101 if (MI.isTransient())
105 FBI->HasCalls = true;
107 // Count processor resources used.
108 if (!SchedModel.hasInstrSchedModel())
110 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
114 for (TargetSchedModel::ProcResIter
115 PI = SchedModel.getWriteProcResBegin(SC),
116 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
117 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
118 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
121 FBI->InstrCount = InstrCount;
123 // Scale the resource cycles so they are comparable.
124 unsigned PROffset = MBB->getNumber() * PRKinds;
125 for (unsigned K = 0; K != PRKinds; ++K)
126 ProcResourceCycles[PROffset + K] =
127 PRCycles[K] * SchedModel.getResourceFactor(K);
133 MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
134 assert(BlockInfo[MBBNum].hasResources() &&
135 "getResources() must be called before getProcResourceCycles()");
136 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
137 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
138 return makeArrayRef(ProcResourceCycles.data() + MBBNum * PRKinds, PRKinds);
142 //===----------------------------------------------------------------------===//
143 // Ensemble utility functions
144 //===----------------------------------------------------------------------===//
146 MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
148 BlockInfo.resize(MTM.BlockInfo.size());
149 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
150 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
151 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
154 // Virtual destructor serves as an anchor.
155 MachineTraceMetrics::Ensemble::~Ensemble() {}
158 MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
159 return MTM.Loops->getLoopFor(MBB);
162 // Update resource-related information in the TraceBlockInfo for MBB.
163 // Only update resources related to the trace above MBB.
164 void MachineTraceMetrics::Ensemble::
165 computeDepthResources(const MachineBasicBlock *MBB) {
166 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
167 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
168 unsigned PROffset = MBB->getNumber() * PRKinds;
170 // Compute resources from trace above. The top block is simple.
173 TBI->Head = MBB->getNumber();
174 std::fill(ProcResourceDepths.begin() + PROffset,
175 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
179 // Compute from the block above. A post-order traversal ensures the
180 // predecessor is always computed first.
181 unsigned PredNum = TBI->Pred->getNumber();
182 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
183 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
184 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
185 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
186 TBI->Head = PredTBI->Head;
188 // Compute per-resource depths.
189 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
190 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
191 for (unsigned K = 0; K != PRKinds; ++K)
192 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
195 // Update resource-related information in the TraceBlockInfo for MBB.
196 // Only update resources related to the trace below MBB.
197 void MachineTraceMetrics::Ensemble::
198 computeHeightResources(const MachineBasicBlock *MBB) {
199 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
200 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
201 unsigned PROffset = MBB->getNumber() * PRKinds;
203 // Compute resources for the current block.
204 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
205 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
207 // The trace tail is done.
209 TBI->Tail = MBB->getNumber();
210 std::copy(PRCycles.begin(), PRCycles.end(),
211 ProcResourceHeights.begin() + PROffset);
215 // Compute from the block below. A post-order traversal ensures the
216 // predecessor is always computed first.
217 unsigned SuccNum = TBI->Succ->getNumber();
218 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
219 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
220 TBI->InstrHeight += SuccTBI->InstrHeight;
221 TBI->Tail = SuccTBI->Tail;
223 // Compute per-resource heights.
224 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
225 for (unsigned K = 0; K != PRKinds; ++K)
226 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
229 // Check if depth resources for MBB are valid and return the TBI.
230 // Return NULL if the resources have been invalidated.
231 const MachineTraceMetrics::TraceBlockInfo*
232 MachineTraceMetrics::Ensemble::
233 getDepthResources(const MachineBasicBlock *MBB) const {
234 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
235 return TBI->hasValidDepth() ? TBI : nullptr;
238 // Check if height resources for MBB are valid and return the TBI.
239 // Return NULL if the resources have been invalidated.
240 const MachineTraceMetrics::TraceBlockInfo*
241 MachineTraceMetrics::Ensemble::
242 getHeightResources(const MachineBasicBlock *MBB) const {
243 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
244 return TBI->hasValidHeight() ? TBI : nullptr;
247 /// Get an array of processor resource depths for MBB. Indexed by processor
248 /// resource kind, this array contains the scaled processor resources consumed
249 /// by all blocks preceding MBB in its trace. It does not include instructions
252 /// Compare TraceBlockInfo::InstrDepth.
254 MachineTraceMetrics::Ensemble::
255 getProcResourceDepths(unsigned MBBNum) const {
256 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
257 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
258 return makeArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds);
261 /// Get an array of processor resource heights for MBB. Indexed by processor
262 /// resource kind, this array contains the scaled processor resources consumed
263 /// by this block and all blocks following it in its trace.
265 /// Compare TraceBlockInfo::InstrHeight.
267 MachineTraceMetrics::Ensemble::
268 getProcResourceHeights(unsigned MBBNum) const {
269 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
270 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
271 return makeArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds);
274 //===----------------------------------------------------------------------===//
275 // Trace Selection Strategies
276 //===----------------------------------------------------------------------===//
278 // A trace selection strategy is implemented as a sub-class of Ensemble. The
279 // trace through a block B is computed by two DFS traversals of the CFG
280 // starting from B. One upwards, and one downwards. During the upwards DFS,
281 // pickTracePred() is called on the post-ordered blocks. During the downwards
282 // DFS, pickTraceSucc() is called in a post-order.
285 // We never allow traces that leave loops, but we do allow traces to enter
286 // nested loops. We also never allow traces to contain back-edges.
288 // This means that a loop header can never appear above the center block of a
289 // trace, except as the trace head. Below the center block, loop exiting edges
292 // Return true if an edge from the From loop to the To loop is leaving a loop.
293 // Either of To and From can be null.
294 static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
295 return From && !From->contains(To);
298 // MinInstrCountEnsemble - Pick the trace that executes the least number of
301 class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
302 const char *getName() const override { return "MinInstr"; }
303 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
304 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
307 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
308 : MachineTraceMetrics::Ensemble(mtm) {}
312 // Select the preferred predecessor for MBB.
313 const MachineBasicBlock*
314 MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
315 if (MBB->pred_empty())
317 const MachineLoop *CurLoop = getLoopFor(MBB);
318 // Don't leave loops, and never follow back-edges.
319 if (CurLoop && MBB == CurLoop->getHeader())
321 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
322 const MachineBasicBlock *Best = nullptr;
323 unsigned BestDepth = 0;
324 for (MachineBasicBlock::const_pred_iterator
325 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
326 const MachineBasicBlock *Pred = *I;
327 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
328 getDepthResources(Pred);
329 // Ignore cycles that aren't natural loops.
332 // Pick the predecessor that would give this block the smallest InstrDepth.
333 unsigned Depth = PredTBI->InstrDepth + CurCount;
334 if (!Best || Depth < BestDepth)
335 Best = Pred, BestDepth = Depth;
340 // Select the preferred successor for MBB.
341 const MachineBasicBlock*
342 MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
343 if (MBB->pred_empty())
345 const MachineLoop *CurLoop = getLoopFor(MBB);
346 const MachineBasicBlock *Best = nullptr;
347 unsigned BestHeight = 0;
348 for (MachineBasicBlock::const_succ_iterator
349 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
350 const MachineBasicBlock *Succ = *I;
351 // Don't consider back-edges.
352 if (CurLoop && Succ == CurLoop->getHeader())
354 // Don't consider successors exiting CurLoop.
355 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
357 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
358 getHeightResources(Succ);
359 // Ignore cycles that aren't natural loops.
362 // Pick the successor that would give this block the smallest InstrHeight.
363 unsigned Height = SuccTBI->InstrHeight;
364 if (!Best || Height < BestHeight)
365 Best = Succ, BestHeight = Height;
370 // Get an Ensemble sub-class for the requested trace strategy.
371 MachineTraceMetrics::Ensemble *
372 MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
373 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
374 Ensemble *&E = Ensembles[strategy];
378 // Allocate new Ensemble on demand.
380 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
381 default: llvm_unreachable("Invalid trace strategy enum");
385 void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
386 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
387 BlockInfo[MBB->getNumber()].invalidate();
388 for (unsigned i = 0; i != TS_NumStrategies; ++i)
390 Ensembles[i]->invalidate(MBB);
393 void MachineTraceMetrics::verifyAnalysis() const {
397 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
398 for (unsigned i = 0; i != TS_NumStrategies; ++i)
400 Ensembles[i]->verify();
404 //===----------------------------------------------------------------------===//
406 //===----------------------------------------------------------------------===//
408 // Traces are built by two CFG traversals. To avoid recomputing too much, use a
409 // set abstraction that confines the search to the current loop, and doesn't
414 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
415 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
416 const MachineLoopInfo *Loops;
418 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
419 const MachineLoopInfo *loops)
420 : Blocks(blocks), Loops(loops), Downward(false) {}
424 // Specialize po_iterator_storage in order to prune the post-order traversal so
425 // it is limited to the current loop and doesn't traverse the loop back edges.
428 class po_iterator_storage<LoopBounds, true> {
431 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
432 void finishPostorder(const MachineBasicBlock*) {}
434 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
435 // Skip already visited To blocks.
436 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
437 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
439 // From is null once when To is the trace center block.
441 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
442 // Don't follow backedges, don't leave FromLoop when going upwards.
443 if ((LB.Downward ? To : From) == FromLoop->getHeader())
445 // Don't leave FromLoop.
446 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
450 // To is a new block. Mark the block as visited in case the CFG has cycles
451 // that MachineLoopInfo didn't recognize as a natural loop.
452 return LB.Visited.insert(To).second;
457 /// Compute the trace through MBB.
458 void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
459 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
460 << MBB->getNumber() << '\n');
461 // Set up loop bounds for the backwards post-order traversal.
462 LoopBounds Bounds(BlockInfo, MTM.Loops);
464 // Run an upwards post-order search for the trace start.
465 Bounds.Downward = false;
466 Bounds.Visited.clear();
467 typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
468 for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
470 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
471 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
472 // All the predecessors have been visited, pick the preferred one.
473 TBI.Pred = pickTracePred(*I);
476 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
480 // The trace leading to I is now known, compute the depth resources.
481 computeDepthResources(*I);
484 // Run a downwards post-order search for the trace end.
485 Bounds.Downward = true;
486 Bounds.Visited.clear();
487 typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
488 for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
490 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
491 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
492 // All the successors have been visited, pick the preferred one.
493 TBI.Succ = pickTraceSucc(*I);
496 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
500 // The trace leaving I is now known, compute the height resources.
501 computeHeightResources(*I);
505 /// Invalidate traces through BadMBB.
507 MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
508 SmallVector<const MachineBasicBlock*, 16> WorkList;
509 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
511 // Invalidate height resources of blocks above MBB.
512 if (BadTBI.hasValidHeight()) {
513 BadTBI.invalidateHeight();
514 WorkList.push_back(BadMBB);
516 const MachineBasicBlock *MBB = WorkList.pop_back_val();
517 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
519 // Find any MBB predecessors that have MBB as their preferred successor.
520 // They are the only ones that need to be invalidated.
521 for (MachineBasicBlock::const_pred_iterator
522 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
523 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
524 if (!TBI.hasValidHeight())
526 if (TBI.Succ == MBB) {
527 TBI.invalidateHeight();
528 WorkList.push_back(*I);
531 // Verify that TBI.Succ is actually a *I successor.
532 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
534 } while (!WorkList.empty());
537 // Invalidate depth resources of blocks below MBB.
538 if (BadTBI.hasValidDepth()) {
539 BadTBI.invalidateDepth();
540 WorkList.push_back(BadMBB);
542 const MachineBasicBlock *MBB = WorkList.pop_back_val();
543 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
545 // Find any MBB successors that have MBB as their preferred predecessor.
546 // They are the only ones that need to be invalidated.
547 for (MachineBasicBlock::const_succ_iterator
548 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
549 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
550 if (!TBI.hasValidDepth())
552 if (TBI.Pred == MBB) {
553 TBI.invalidateDepth();
554 WorkList.push_back(*I);
557 // Verify that TBI.Pred is actually a *I predecessor.
558 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
560 } while (!WorkList.empty());
563 // Clear any per-instruction data. We only have to do this for BadMBB itself
564 // because the instructions in that block may change. Other blocks may be
565 // invalidated, but their instructions will stay the same, so there is no
566 // need to erase the Cycle entries. They will be overwritten when we
568 for (const auto &I : *BadMBB)
572 void MachineTraceMetrics::Ensemble::verify() const {
574 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
575 "Outdated BlockInfo size");
576 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
577 const TraceBlockInfo &TBI = BlockInfo[Num];
578 if (TBI.hasValidDepth() && TBI.Pred) {
579 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
580 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
581 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
582 "Trace is broken, depth should have been invalidated.");
583 const MachineLoop *Loop = getLoopFor(MBB);
584 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
586 if (TBI.hasValidHeight() && TBI.Succ) {
587 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
588 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
589 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
590 "Trace is broken, height should have been invalidated.");
591 const MachineLoop *Loop = getLoopFor(MBB);
592 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
593 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
594 "Trace contains backedge");
600 //===----------------------------------------------------------------------===//
602 //===----------------------------------------------------------------------===//
604 // Compute the depth and height of each instruction based on data dependencies
605 // and instruction latencies. These cycle numbers assume that the CPU can issue
606 // an infinite number of instructions per cycle as long as their dependencies
609 // A data dependency is represented as a defining MI and operand numbers on the
610 // defining and using MI.
613 const MachineInstr *DefMI;
617 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
618 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
620 /// Create a DataDep from an SSA form virtual register.
621 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
623 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
624 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
625 assert(!DefI.atEnd() && "Register has no defs");
626 DefMI = DefI->getParent();
627 DefOp = DefI.getOperandNo();
628 assert((++DefI).atEnd() && "Register has multiple defs");
633 // Get the input data dependencies that must be ready before UseMI can issue.
634 // Return true if UseMI has any physreg operands.
635 static bool getDataDeps(const MachineInstr *UseMI,
636 SmallVectorImpl<DataDep> &Deps,
637 const MachineRegisterInfo *MRI) {
638 bool HasPhysRegs = false;
639 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
642 unsigned Reg = MO->getReg();
645 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
649 // Collect virtual register reads.
651 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
656 // Get the input data dependencies of a PHI instruction, using Pred as the
657 // preferred predecessor.
658 // This will add at most one dependency to Deps.
659 static void getPHIDeps(const MachineInstr *UseMI,
660 SmallVectorImpl<DataDep> &Deps,
661 const MachineBasicBlock *Pred,
662 const MachineRegisterInfo *MRI) {
663 // No predecessor at the beginning of a trace. Ignore dependencies.
666 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
667 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
668 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
669 unsigned Reg = UseMI->getOperand(i).getReg();
670 Deps.push_back(DataDep(MRI, Reg, i));
676 // Keep track of physreg data dependencies by recording each live register unit.
677 // Associate each regunit with an instruction operand. Depending on the
678 // direction instructions are scanned, it could be the operand that defined the
679 // regunit, or the highest operand to read the regunit.
684 const MachineInstr *MI;
687 unsigned getSparseSetIndex() const { return RegUnit; }
689 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {}
693 // Identify physreg dependencies for UseMI, and update the live regunit
694 // tracking set when scanning instructions downwards.
695 static void updatePhysDepsDownwards(const MachineInstr *UseMI,
696 SmallVectorImpl<DataDep> &Deps,
697 SparseSet<LiveRegUnit> &RegUnits,
698 const TargetRegisterInfo *TRI) {
699 SmallVector<unsigned, 8> Kills;
700 SmallVector<unsigned, 8> LiveDefOps;
702 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
705 unsigned Reg = MO->getReg();
706 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
708 // Track live defs and kills for updating RegUnits.
711 Kills.push_back(Reg);
713 LiveDefOps.push_back(MO.getOperandNo());
714 } else if (MO->isKill())
715 Kills.push_back(Reg);
716 // Identify dependencies.
719 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
720 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
721 if (I == RegUnits.end())
723 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
728 // Update RegUnits to reflect live registers after UseMI.
730 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
731 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
732 RegUnits.erase(*Units);
734 // Second, live defs.
735 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
736 unsigned DefOp = LiveDefOps[i];
737 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
738 Units.isValid(); ++Units) {
739 LiveRegUnit &LRU = RegUnits[*Units];
746 /// The length of the critical path through a trace is the maximum of two path
749 /// 1. The maximum height+depth over all instructions in the trace center block.
751 /// 2. The longest cross-block dependency chain. For small blocks, it is
752 /// possible that the critical path through the trace doesn't include any
753 /// instructions in the block.
755 /// This function computes the second number from the live-in list of the
757 unsigned MachineTraceMetrics::Ensemble::
758 computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
759 assert(TBI.HasValidInstrDepths && "Missing depth info");
760 assert(TBI.HasValidInstrHeights && "Missing height info");
762 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
763 const LiveInReg &LIR = TBI.LiveIns[i];
764 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
766 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
767 // Ignore dependencies outside the current trace.
768 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
769 if (!DefTBI.isUsefulDominator(TBI))
771 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
772 MaxLen = std::max(MaxLen, Len);
777 /// Compute instruction depths for all instructions above or in MBB in its
778 /// trace. This assumes that the trace through MBB has already been computed.
779 void MachineTraceMetrics::Ensemble::
780 computeInstrDepths(const MachineBasicBlock *MBB) {
781 // The top of the trace may already be computed, and HasValidInstrDepths
782 // implies Head->HasValidInstrDepths, so we only need to start from the first
783 // block in the trace that needs to be recomputed.
784 SmallVector<const MachineBasicBlock*, 8> Stack;
786 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
787 assert(TBI.hasValidDepth() && "Incomplete trace");
788 if (TBI.HasValidInstrDepths)
790 Stack.push_back(MBB);
794 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
795 // in the trace. We should track any live-out physregs that were defined in
796 // the trace. This is quite rare in SSA form, typically created by CSE
797 // hoisting a compare.
798 SparseSet<LiveRegUnit> RegUnits;
799 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
801 // Go through trace blocks in top-down order, stopping after the center block.
802 SmallVector<DataDep, 8> Deps;
803 while (!Stack.empty()) {
804 MBB = Stack.pop_back_val();
805 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
806 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
807 TBI.HasValidInstrDepths = true;
808 TBI.CriticalPath = 0;
810 // Print out resource depths here as well.
812 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
813 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
814 for (unsigned K = 0; K != PRDepths.size(); ++K)
816 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
817 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
818 << MTM.SchedModel.getProcResource(K)->Name << " ("
819 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
823 // Also compute the critical path length through MBB when possible.
824 if (TBI.HasValidInstrHeights)
825 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
827 for (const auto &UseMI : *MBB) {
828 // Collect all data dependencies.
831 getPHIDeps(&UseMI, Deps, TBI.Pred, MTM.MRI);
832 else if (getDataDeps(&UseMI, Deps, MTM.MRI))
833 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
835 // Filter and process dependencies, computing the earliest issue cycle.
837 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
838 const DataDep &Dep = Deps[i];
839 const TraceBlockInfo&DepTBI =
840 BlockInfo[Dep.DefMI->getParent()->getNumber()];
841 // Ignore dependencies from outside the current trace.
842 if (!DepTBI.isUsefulDominator(TBI))
844 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
845 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
846 // Add latency if DefMI is a real instruction. Transients get latency 0.
847 if (!Dep.DefMI->isTransient())
848 DepCycle += MTM.SchedModel
849 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
850 Cycle = std::max(Cycle, DepCycle);
852 // Remember the instruction depth.
853 InstrCycles &MICycles = Cycles[&UseMI];
854 MICycles.Depth = Cycle;
856 if (!TBI.HasValidInstrHeights) {
857 DEBUG(dbgs() << Cycle << '\t' << UseMI);
860 // Update critical path length.
861 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
862 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
867 // Identify physreg dependencies for MI when scanning instructions upwards.
868 // Return the issue height of MI after considering any live regunits.
869 // Height is the issue height computed from virtual register dependencies alone.
870 static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
871 SparseSet<LiveRegUnit> &RegUnits,
872 const TargetSchedModel &SchedModel,
873 const TargetInstrInfo *TII,
874 const TargetRegisterInfo *TRI) {
875 SmallVector<unsigned, 8> ReadOps;
876 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
879 unsigned Reg = MO->getReg();
880 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
883 ReadOps.push_back(MO.getOperandNo());
886 // This is a def of Reg. Remove corresponding entries from RegUnits, and
887 // update MI Height to consider the physreg dependencies.
888 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
889 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
890 if (I == RegUnits.end())
892 unsigned DepHeight = I->Cycle;
893 if (!MI->isTransient()) {
894 // We may not know the UseMI of this dependency, if it came from the
895 // live-in list. SchedModel can handle a NULL UseMI.
896 DepHeight += SchedModel
897 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op);
899 Height = std::max(Height, DepHeight);
900 // This regunit is dead above MI.
905 // Now we know the height of MI. Update any regunits read.
906 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
907 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
908 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
909 LiveRegUnit &LRU = RegUnits[*Units];
910 // Set the height to the highest reader of the unit.
911 if (LRU.Cycle <= Height && LRU.MI != MI) {
923 typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
925 // Push the height of DefMI upwards if required to match UseMI.
926 // Return true if this is the first time DefMI was seen.
927 static bool pushDepHeight(const DataDep &Dep,
928 const MachineInstr *UseMI, unsigned UseHeight,
929 MIHeightMap &Heights,
930 const TargetSchedModel &SchedModel,
931 const TargetInstrInfo *TII) {
932 // Adjust height by Dep.DefMI latency.
933 if (!Dep.DefMI->isTransient())
934 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
937 // Update Heights[DefMI] to be the maximum height seen.
938 MIHeightMap::iterator I;
940 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
944 // DefMI has been pushed before. Give it the max height.
945 if (I->second < UseHeight)
946 I->second = UseHeight;
950 /// Assuming that the virtual register defined by DefMI:DefOp was used by
951 /// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
952 /// when reaching the block that contains DefMI.
953 void MachineTraceMetrics::Ensemble::
954 addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
955 ArrayRef<const MachineBasicBlock*> Trace) {
956 assert(!Trace.empty() && "Trace should contain at least one block");
957 unsigned Reg = DefMI->getOperand(DefOp).getReg();
958 assert(TargetRegisterInfo::isVirtualRegister(Reg));
959 const MachineBasicBlock *DefMBB = DefMI->getParent();
961 // Reg is live-in to all blocks in Trace that follow DefMBB.
962 for (unsigned i = Trace.size(); i; --i) {
963 const MachineBasicBlock *MBB = Trace[i-1];
966 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
967 // Just add the register. The height will be updated later.
968 TBI.LiveIns.push_back(Reg);
972 /// Compute instruction heights in the trace through MBB. This updates MBB and
973 /// the blocks below it in the trace. It is assumed that the trace has already
975 void MachineTraceMetrics::Ensemble::
976 computeInstrHeights(const MachineBasicBlock *MBB) {
977 // The bottom of the trace may already be computed.
978 // Find the blocks that need updating.
979 SmallVector<const MachineBasicBlock*, 8> Stack;
981 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
982 assert(TBI.hasValidHeight() && "Incomplete trace");
983 if (TBI.HasValidInstrHeights)
985 Stack.push_back(MBB);
990 // As we move upwards in the trace, keep track of instructions that are
991 // required by deeper trace instructions. Map MI -> height required so far.
994 // For physregs, the def isn't known when we see the use.
995 // Instead, keep track of the highest use of each regunit.
996 SparseSet<LiveRegUnit> RegUnits;
997 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
999 // If the bottom of the trace was already precomputed, initialize heights
1000 // from its live-in list.
1001 // MBB is the highest precomputed block in the trace.
1003 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1004 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1005 LiveInReg LI = TBI.LiveIns[i];
1006 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1007 // For virtual registers, the def latency is included.
1008 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1009 if (Height < LI.Height)
1012 // For register units, the def latency is not included because we don't
1013 // know the def yet.
1014 RegUnits[LI.Reg].Cycle = LI.Height;
1019 // Go through the trace blocks in bottom-up order.
1020 SmallVector<DataDep, 8> Deps;
1021 for (;!Stack.empty(); Stack.pop_back()) {
1023 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1024 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1025 TBI.HasValidInstrHeights = true;
1026 TBI.CriticalPath = 0;
1029 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1030 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1031 for (unsigned K = 0; K != PRHeights.size(); ++K)
1033 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1034 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1035 << MTM.SchedModel.getProcResource(K)->Name << " ("
1036 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1040 // Get dependencies from PHIs in the trace successor.
1041 const MachineBasicBlock *Succ = TBI.Succ;
1042 // If MBB is the last block in the trace, and it has a back-edge to the
1043 // loop header, get loop-carried dependencies from PHIs in the header. For
1044 // that purpose, pretend that all the loop header PHIs have height 0.
1046 if (const MachineLoop *Loop = getLoopFor(MBB))
1047 if (MBB->isSuccessor(Loop->getHeader()))
1048 Succ = Loop->getHeader();
1051 for (const auto &PHI : *Succ) {
1055 getPHIDeps(&PHI, Deps, MBB, MTM.MRI);
1056 if (!Deps.empty()) {
1057 // Loop header PHI heights are all 0.
1058 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1059 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
1060 if (pushDepHeight(Deps.front(), &PHI, Height,
1061 Heights, MTM.SchedModel, MTM.TII))
1062 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
1067 // Go through the block backwards.
1068 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1070 const MachineInstr *MI = --BI;
1072 // Find the MI height as determined by virtual register uses in the
1075 MIHeightMap::iterator HeightI = Heights.find(MI);
1076 if (HeightI != Heights.end()) {
1077 Cycle = HeightI->second;
1078 // We won't be seeing any more MI uses.
1079 Heights.erase(HeightI);
1082 // Don't process PHI deps. They depend on the specific predecessor, and
1083 // we'll get them when visiting the predecessor.
1085 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1087 // There may also be regunit dependencies to include in the height.
1089 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
1090 MTM.SchedModel, MTM.TII, MTM.TRI);
1092 // Update the required height of any virtual registers read by MI.
1093 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
1094 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
1095 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
1097 InstrCycles &MICycles = Cycles[MI];
1098 MICycles.Height = Cycle;
1099 if (!TBI.HasValidInstrDepths) {
1100 DEBUG(dbgs() << Cycle << '\t' << *MI);
1103 // Update critical path length.
1104 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1105 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
1108 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1109 // height because the final height isn't known until now.
1110 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
1111 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1112 LiveInReg &LIR = TBI.LiveIns[i];
1113 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1114 LIR.Height = Heights.lookup(DefMI);
1115 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1118 // Transfer the live regunits to the live-in list.
1119 for (SparseSet<LiveRegUnit>::const_iterator
1120 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1121 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1122 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1123 << '@' << RI->Cycle);
1125 DEBUG(dbgs() << '\n');
1127 if (!TBI.HasValidInstrDepths)
1129 // Add live-ins to the critical path length.
1130 TBI.CriticalPath = std::max(TBI.CriticalPath,
1131 computeCrossBlockCriticalPath(TBI));
1132 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
1136 MachineTraceMetrics::Trace
1137 MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1138 // FIXME: Check cache tags, recompute as needed.
1140 computeInstrDepths(MBB);
1141 computeInstrHeights(MBB);
1142 return Trace(*this, BlockInfo[MBB->getNumber()]);
1146 MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1147 assert(MI && "Not an instruction.");
1148 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1149 "MI must be in the trace center block");
1150 InstrCycles Cyc = getInstrCycles(MI);
1151 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1155 MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1156 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1157 SmallVector<DataDep, 1> Deps;
1158 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1159 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1160 DataDep &Dep = Deps.front();
1161 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1162 // Add latency if DefMI is a real instruction. Transients get latency 0.
1163 if (!Dep.DefMI->isTransient())
1164 DepCycle += TE.MTM.SchedModel
1165 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp);
1169 /// When bottom is set include instructions in current block in estimate.
1170 unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
1171 // Find the limiting processor resource.
1172 // Numbers have been pre-scaled to be comparable.
1174 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1176 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1177 for (unsigned K = 0; K != PRDepths.size(); ++K)
1178 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1180 for (unsigned K = 0; K != PRDepths.size(); ++K)
1181 PRMax = std::max(PRMax, PRDepths[K]);
1183 // Convert to cycle count.
1184 PRMax = TE.MTM.getCycles(PRMax);
1186 /// All instructions before current block
1187 unsigned Instrs = TBI.InstrDepth;
1188 // plus instructions in current block
1190 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
1191 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1193 // Assume issue width 1 without a schedule model.
1194 return std::max(Instrs, PRMax);
1197 unsigned MachineTraceMetrics::Trace::getResourceLength(
1198 ArrayRef<const MachineBasicBlock *> Extrablocks,
1199 ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1200 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
1201 // Add up resources above and below the center block.
1202 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1203 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1206 // Capture computing cycles from extra instructions
1207 auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
1208 unsigned ResourceIdx)
1210 unsigned Cycles = 0;
1211 for (unsigned I = 0; I != Instrs.size(); ++I) {
1212 const MCSchedClassDesc *SC = Instrs[I];
1215 for (TargetSchedModel::ProcResIter
1216 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1217 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
1219 if (PI->ProcResourceIdx != ResourceIdx)
1222 (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
1228 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1229 unsigned PRCycles = PRDepths[K] + PRHeights[K];
1230 for (unsigned I = 0; I != Extrablocks.size(); ++I)
1231 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
1232 PRCycles += extraCycles(ExtraInstrs, K);
1233 PRCycles -= extraCycles(RemoveInstrs, K);
1234 PRMax = std::max(PRMax, PRCycles);
1236 // Convert to cycle count.
1237 PRMax = TE.MTM.getCycles(PRMax);
1239 // Instrs: #instructions in current trace outside current block.
1240 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1241 // Add instruction count from the extra blocks.
1242 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1243 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
1244 Instrs += ExtraInstrs.size();
1245 Instrs -= RemoveInstrs.size();
1246 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1248 // Assume issue width 1 without a schedule model.
1249 return std::max(Instrs, PRMax);
1252 bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr *DefMI,
1253 const MachineInstr *UseMI) const {
1254 if (DefMI->getParent() == UseMI->getParent())
1257 const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI->getParent()->getNumber()];
1258 const TraceBlockInfo &TBI = TE.BlockInfo[UseMI->getParent()->getNumber()];
1260 return DepTBI.isUsefulDominator(TBI);
1263 void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1264 OS << getName() << " ensemble:\n";
1265 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1266 OS << " BB#" << i << '\t';
1267 BlockInfo[i].print(OS);
1272 void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1273 if (hasValidDepth()) {
1274 OS << "depth=" << InstrDepth;
1276 OS << " pred=BB#" << Pred->getNumber();
1279 OS << " head=BB#" << Head;
1280 if (HasValidInstrDepths)
1283 OS << "depth invalid";
1285 if (hasValidHeight()) {
1286 OS << "height=" << InstrHeight;
1288 OS << " succ=BB#" << Succ->getNumber();
1291 OS << " tail=BB#" << Tail;
1292 if (HasValidInstrHeights)
1295 OS << "height invalid";
1296 if (HasValidInstrDepths && HasValidInstrHeights)
1297 OS << ", crit=" << CriticalPath;
1300 void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
1301 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1303 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1304 << " --> BB#" << TBI.Tail << ':';
1305 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1306 OS << ' ' << getInstrCount() << " instrs.";
1307 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1308 OS << ' ' << TBI.CriticalPath << " cycles.";
1310 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
1311 OS << "\nBB#" << MBBNum;
1312 while (Block->hasValidDepth() && Block->Pred) {
1313 unsigned Num = Block->Pred->getNumber();
1314 OS << " <- BB#" << Num;
1315 Block = &TE.BlockInfo[Num];
1320 while (Block->hasValidHeight() && Block->Succ) {
1321 unsigned Num = Block->Succ->getNumber();
1322 OS << " -> BB#" << Num;
1323 Block = &TE.BlockInfo[Num];