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 ArrayRef<unsigned>(ProcResourceCycles.data() + MBBNum * PRKinds,
143 //===----------------------------------------------------------------------===//
144 // Ensemble utility functions
145 //===----------------------------------------------------------------------===//
147 MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
149 BlockInfo.resize(MTM.BlockInfo.size());
150 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
151 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
152 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
155 // Virtual destructor serves as an anchor.
156 MachineTraceMetrics::Ensemble::~Ensemble() {}
159 MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
160 return MTM.Loops->getLoopFor(MBB);
163 // Update resource-related information in the TraceBlockInfo for MBB.
164 // Only update resources related to the trace above MBB.
165 void MachineTraceMetrics::Ensemble::
166 computeDepthResources(const MachineBasicBlock *MBB) {
167 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
168 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
169 unsigned PROffset = MBB->getNumber() * PRKinds;
171 // Compute resources from trace above. The top block is simple.
174 TBI->Head = MBB->getNumber();
175 std::fill(ProcResourceDepths.begin() + PROffset,
176 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
180 // Compute from the block above. A post-order traversal ensures the
181 // predecessor is always computed first.
182 unsigned PredNum = TBI->Pred->getNumber();
183 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
184 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
185 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
186 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
187 TBI->Head = PredTBI->Head;
189 // Compute per-resource depths.
190 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
191 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
192 for (unsigned K = 0; K != PRKinds; ++K)
193 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
196 // Update resource-related information in the TraceBlockInfo for MBB.
197 // Only update resources related to the trace below MBB.
198 void MachineTraceMetrics::Ensemble::
199 computeHeightResources(const MachineBasicBlock *MBB) {
200 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
201 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
202 unsigned PROffset = MBB->getNumber() * PRKinds;
204 // Compute resources for the current block.
205 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
206 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
208 // The trace tail is done.
210 TBI->Tail = MBB->getNumber();
211 std::copy(PRCycles.begin(), PRCycles.end(),
212 ProcResourceHeights.begin() + PROffset);
216 // Compute from the block below. A post-order traversal ensures the
217 // predecessor is always computed first.
218 unsigned SuccNum = TBI->Succ->getNumber();
219 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
220 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
221 TBI->InstrHeight += SuccTBI->InstrHeight;
222 TBI->Tail = SuccTBI->Tail;
224 // Compute per-resource heights.
225 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
226 for (unsigned K = 0; K != PRKinds; ++K)
227 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
230 // Check if depth resources for MBB are valid and return the TBI.
231 // Return NULL if the resources have been invalidated.
232 const MachineTraceMetrics::TraceBlockInfo*
233 MachineTraceMetrics::Ensemble::
234 getDepthResources(const MachineBasicBlock *MBB) const {
235 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
236 return TBI->hasValidDepth() ? TBI : nullptr;
239 // Check if height resources for MBB are valid and return the TBI.
240 // Return NULL if the resources have been invalidated.
241 const MachineTraceMetrics::TraceBlockInfo*
242 MachineTraceMetrics::Ensemble::
243 getHeightResources(const MachineBasicBlock *MBB) const {
244 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
245 return TBI->hasValidHeight() ? TBI : nullptr;
248 /// Get an array of processor resource depths for MBB. Indexed by processor
249 /// resource kind, this array contains the scaled processor resources consumed
250 /// by all blocks preceding MBB in its trace. It does not include instructions
253 /// Compare TraceBlockInfo::InstrDepth.
255 MachineTraceMetrics::Ensemble::
256 getProcResourceDepths(unsigned MBBNum) const {
257 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
258 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
259 return ArrayRef<unsigned>(ProcResourceDepths.data() + MBBNum * PRKinds,
263 /// Get an array of processor resource heights for MBB. Indexed by processor
264 /// resource kind, this array contains the scaled processor resources consumed
265 /// by this block and all blocks following it in its trace.
267 /// Compare TraceBlockInfo::InstrHeight.
269 MachineTraceMetrics::Ensemble::
270 getProcResourceHeights(unsigned MBBNum) const {
271 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
272 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
273 return ArrayRef<unsigned>(ProcResourceHeights.data() + MBBNum * PRKinds,
277 //===----------------------------------------------------------------------===//
278 // Trace Selection Strategies
279 //===----------------------------------------------------------------------===//
281 // A trace selection strategy is implemented as a sub-class of Ensemble. The
282 // trace through a block B is computed by two DFS traversals of the CFG
283 // starting from B. One upwards, and one downwards. During the upwards DFS,
284 // pickTracePred() is called on the post-ordered blocks. During the downwards
285 // DFS, pickTraceSucc() is called in a post-order.
288 // We never allow traces that leave loops, but we do allow traces to enter
289 // nested loops. We also never allow traces to contain back-edges.
291 // This means that a loop header can never appear above the center block of a
292 // trace, except as the trace head. Below the center block, loop exiting edges
295 // Return true if an edge from the From loop to the To loop is leaving a loop.
296 // Either of To and From can be null.
297 static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
298 return From && !From->contains(To);
301 // MinInstrCountEnsemble - Pick the trace that executes the least number of
304 class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
305 const char *getName() const override { return "MinInstr"; }
306 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
307 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
310 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
311 : MachineTraceMetrics::Ensemble(mtm) {}
315 // Select the preferred predecessor for MBB.
316 const MachineBasicBlock*
317 MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
318 if (MBB->pred_empty())
320 const MachineLoop *CurLoop = getLoopFor(MBB);
321 // Don't leave loops, and never follow back-edges.
322 if (CurLoop && MBB == CurLoop->getHeader())
324 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
325 const MachineBasicBlock *Best = nullptr;
326 unsigned BestDepth = 0;
327 for (MachineBasicBlock::const_pred_iterator
328 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
329 const MachineBasicBlock *Pred = *I;
330 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
331 getDepthResources(Pred);
332 // Ignore cycles that aren't natural loops.
335 // Pick the predecessor that would give this block the smallest InstrDepth.
336 unsigned Depth = PredTBI->InstrDepth + CurCount;
337 if (!Best || Depth < BestDepth)
338 Best = Pred, BestDepth = Depth;
343 // Select the preferred successor for MBB.
344 const MachineBasicBlock*
345 MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
346 if (MBB->pred_empty())
348 const MachineLoop *CurLoop = getLoopFor(MBB);
349 const MachineBasicBlock *Best = nullptr;
350 unsigned BestHeight = 0;
351 for (MachineBasicBlock::const_succ_iterator
352 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
353 const MachineBasicBlock *Succ = *I;
354 // Don't consider back-edges.
355 if (CurLoop && Succ == CurLoop->getHeader())
357 // Don't consider successors exiting CurLoop.
358 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
360 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
361 getHeightResources(Succ);
362 // Ignore cycles that aren't natural loops.
365 // Pick the successor that would give this block the smallest InstrHeight.
366 unsigned Height = SuccTBI->InstrHeight;
367 if (!Best || Height < BestHeight)
368 Best = Succ, BestHeight = Height;
373 // Get an Ensemble sub-class for the requested trace strategy.
374 MachineTraceMetrics::Ensemble *
375 MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
376 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
377 Ensemble *&E = Ensembles[strategy];
381 // Allocate new Ensemble on demand.
383 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
384 default: llvm_unreachable("Invalid trace strategy enum");
388 void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
389 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
390 BlockInfo[MBB->getNumber()].invalidate();
391 for (unsigned i = 0; i != TS_NumStrategies; ++i)
393 Ensembles[i]->invalidate(MBB);
396 void MachineTraceMetrics::verifyAnalysis() const {
400 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
401 for (unsigned i = 0; i != TS_NumStrategies; ++i)
403 Ensembles[i]->verify();
407 //===----------------------------------------------------------------------===//
409 //===----------------------------------------------------------------------===//
411 // Traces are built by two CFG traversals. To avoid recomputing too much, use a
412 // set abstraction that confines the search to the current loop, and doesn't
417 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
418 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
419 const MachineLoopInfo *Loops;
421 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
422 const MachineLoopInfo *loops)
423 : Blocks(blocks), Loops(loops), Downward(false) {}
427 // Specialize po_iterator_storage in order to prune the post-order traversal so
428 // it is limited to the current loop and doesn't traverse the loop back edges.
431 class po_iterator_storage<LoopBounds, true> {
434 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
435 void finishPostorder(const MachineBasicBlock*) {}
437 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
438 // Skip already visited To blocks.
439 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
440 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
442 // From is null once when To is the trace center block.
444 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
445 // Don't follow backedges, don't leave FromLoop when going upwards.
446 if ((LB.Downward ? To : From) == FromLoop->getHeader())
448 // Don't leave FromLoop.
449 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
453 // To is a new block. Mark the block as visited in case the CFG has cycles
454 // that MachineLoopInfo didn't recognize as a natural loop.
455 return LB.Visited.insert(To);
460 /// Compute the trace through MBB.
461 void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
462 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
463 << MBB->getNumber() << '\n');
464 // Set up loop bounds for the backwards post-order traversal.
465 LoopBounds Bounds(BlockInfo, MTM.Loops);
467 // Run an upwards post-order search for the trace start.
468 Bounds.Downward = false;
469 Bounds.Visited.clear();
470 typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
471 for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
473 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
474 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
475 // All the predecessors have been visited, pick the preferred one.
476 TBI.Pred = pickTracePred(*I);
479 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
483 // The trace leading to I is now known, compute the depth resources.
484 computeDepthResources(*I);
487 // Run a downwards post-order search for the trace end.
488 Bounds.Downward = true;
489 Bounds.Visited.clear();
490 typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
491 for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
493 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
494 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
495 // All the successors have been visited, pick the preferred one.
496 TBI.Succ = pickTraceSucc(*I);
499 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
503 // The trace leaving I is now known, compute the height resources.
504 computeHeightResources(*I);
508 /// Invalidate traces through BadMBB.
510 MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
511 SmallVector<const MachineBasicBlock*, 16> WorkList;
512 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
514 // Invalidate height resources of blocks above MBB.
515 if (BadTBI.hasValidHeight()) {
516 BadTBI.invalidateHeight();
517 WorkList.push_back(BadMBB);
519 const MachineBasicBlock *MBB = WorkList.pop_back_val();
520 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
522 // Find any MBB predecessors that have MBB as their preferred successor.
523 // They are the only ones that need to be invalidated.
524 for (MachineBasicBlock::const_pred_iterator
525 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
526 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
527 if (!TBI.hasValidHeight())
529 if (TBI.Succ == MBB) {
530 TBI.invalidateHeight();
531 WorkList.push_back(*I);
534 // Verify that TBI.Succ is actually a *I successor.
535 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
537 } while (!WorkList.empty());
540 // Invalidate depth resources of blocks below MBB.
541 if (BadTBI.hasValidDepth()) {
542 BadTBI.invalidateDepth();
543 WorkList.push_back(BadMBB);
545 const MachineBasicBlock *MBB = WorkList.pop_back_val();
546 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
548 // Find any MBB successors that have MBB as their preferred predecessor.
549 // They are the only ones that need to be invalidated.
550 for (MachineBasicBlock::const_succ_iterator
551 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
552 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
553 if (!TBI.hasValidDepth())
555 if (TBI.Pred == MBB) {
556 TBI.invalidateDepth();
557 WorkList.push_back(*I);
560 // Verify that TBI.Pred is actually a *I predecessor.
561 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
563 } while (!WorkList.empty());
566 // Clear any per-instruction data. We only have to do this for BadMBB itself
567 // because the instructions in that block may change. Other blocks may be
568 // invalidated, but their instructions will stay the same, so there is no
569 // need to erase the Cycle entries. They will be overwritten when we
571 for (const auto &I : *BadMBB)
575 void MachineTraceMetrics::Ensemble::verify() const {
577 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
578 "Outdated BlockInfo size");
579 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
580 const TraceBlockInfo &TBI = BlockInfo[Num];
581 if (TBI.hasValidDepth() && TBI.Pred) {
582 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
583 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
584 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
585 "Trace is broken, depth should have been invalidated.");
586 const MachineLoop *Loop = getLoopFor(MBB);
587 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
589 if (TBI.hasValidHeight() && TBI.Succ) {
590 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
591 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
592 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
593 "Trace is broken, height should have been invalidated.");
594 const MachineLoop *Loop = getLoopFor(MBB);
595 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
596 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
597 "Trace contains backedge");
603 //===----------------------------------------------------------------------===//
605 //===----------------------------------------------------------------------===//
607 // Compute the depth and height of each instruction based on data dependencies
608 // and instruction latencies. These cycle numbers assume that the CPU can issue
609 // an infinite number of instructions per cycle as long as their dependencies
612 // A data dependency is represented as a defining MI and operand numbers on the
613 // defining and using MI.
616 const MachineInstr *DefMI;
620 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
621 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
623 /// Create a DataDep from an SSA form virtual register.
624 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
626 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
627 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
628 assert(!DefI.atEnd() && "Register has no defs");
629 DefMI = DefI->getParent();
630 DefOp = DefI.getOperandNo();
631 assert((++DefI).atEnd() && "Register has multiple defs");
636 // Get the input data dependencies that must be ready before UseMI can issue.
637 // Return true if UseMI has any physreg operands.
638 static bool getDataDeps(const MachineInstr *UseMI,
639 SmallVectorImpl<DataDep> &Deps,
640 const MachineRegisterInfo *MRI) {
641 bool HasPhysRegs = false;
642 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
645 unsigned Reg = MO->getReg();
648 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
652 // Collect virtual register reads.
654 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
659 // Get the input data dependencies of a PHI instruction, using Pred as the
660 // preferred predecessor.
661 // This will add at most one dependency to Deps.
662 static void getPHIDeps(const MachineInstr *UseMI,
663 SmallVectorImpl<DataDep> &Deps,
664 const MachineBasicBlock *Pred,
665 const MachineRegisterInfo *MRI) {
666 // No predecessor at the beginning of a trace. Ignore dependencies.
669 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
670 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
671 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
672 unsigned Reg = UseMI->getOperand(i).getReg();
673 Deps.push_back(DataDep(MRI, Reg, i));
679 // Keep track of physreg data dependencies by recording each live register unit.
680 // Associate each regunit with an instruction operand. Depending on the
681 // direction instructions are scanned, it could be the operand that defined the
682 // regunit, or the highest operand to read the regunit.
687 const MachineInstr *MI;
690 unsigned getSparseSetIndex() const { return RegUnit; }
692 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {}
696 // Identify physreg dependencies for UseMI, and update the live regunit
697 // tracking set when scanning instructions downwards.
698 static void updatePhysDepsDownwards(const MachineInstr *UseMI,
699 SmallVectorImpl<DataDep> &Deps,
700 SparseSet<LiveRegUnit> &RegUnits,
701 const TargetRegisterInfo *TRI) {
702 SmallVector<unsigned, 8> Kills;
703 SmallVector<unsigned, 8> LiveDefOps;
705 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
708 unsigned Reg = MO->getReg();
709 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
711 // Track live defs and kills for updating RegUnits.
714 Kills.push_back(Reg);
716 LiveDefOps.push_back(MO.getOperandNo());
717 } else if (MO->isKill())
718 Kills.push_back(Reg);
719 // Identify dependencies.
722 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
723 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
724 if (I == RegUnits.end())
726 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
731 // Update RegUnits to reflect live registers after UseMI.
733 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
734 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
735 RegUnits.erase(*Units);
737 // Second, live defs.
738 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
739 unsigned DefOp = LiveDefOps[i];
740 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
741 Units.isValid(); ++Units) {
742 LiveRegUnit &LRU = RegUnits[*Units];
749 /// The length of the critical path through a trace is the maximum of two path
752 /// 1. The maximum height+depth over all instructions in the trace center block.
754 /// 2. The longest cross-block dependency chain. For small blocks, it is
755 /// possible that the critical path through the trace doesn't include any
756 /// instructions in the block.
758 /// This function computes the second number from the live-in list of the
760 unsigned MachineTraceMetrics::Ensemble::
761 computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
762 assert(TBI.HasValidInstrDepths && "Missing depth info");
763 assert(TBI.HasValidInstrHeights && "Missing height info");
765 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
766 const LiveInReg &LIR = TBI.LiveIns[i];
767 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
769 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
770 // Ignore dependencies outside the current trace.
771 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
772 if (!DefTBI.isUsefulDominator(TBI))
774 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
775 MaxLen = std::max(MaxLen, Len);
780 /// Compute instruction depths for all instructions above or in MBB in its
781 /// trace. This assumes that the trace through MBB has already been computed.
782 void MachineTraceMetrics::Ensemble::
783 computeInstrDepths(const MachineBasicBlock *MBB) {
784 // The top of the trace may already be computed, and HasValidInstrDepths
785 // implies Head->HasValidInstrDepths, so we only need to start from the first
786 // block in the trace that needs to be recomputed.
787 SmallVector<const MachineBasicBlock*, 8> Stack;
789 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
790 assert(TBI.hasValidDepth() && "Incomplete trace");
791 if (TBI.HasValidInstrDepths)
793 Stack.push_back(MBB);
797 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
798 // in the trace. We should track any live-out physregs that were defined in
799 // the trace. This is quite rare in SSA form, typically created by CSE
800 // hoisting a compare.
801 SparseSet<LiveRegUnit> RegUnits;
802 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
804 // Go through trace blocks in top-down order, stopping after the center block.
805 SmallVector<DataDep, 8> Deps;
806 while (!Stack.empty()) {
807 MBB = Stack.pop_back_val();
808 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
809 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
810 TBI.HasValidInstrDepths = true;
811 TBI.CriticalPath = 0;
813 // Print out resource depths here as well.
815 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
816 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
817 for (unsigned K = 0; K != PRDepths.size(); ++K)
819 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
820 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
821 << MTM.SchedModel.getProcResource(K)->Name << " ("
822 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
826 // Also compute the critical path length through MBB when possible.
827 if (TBI.HasValidInstrHeights)
828 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
830 for (const auto &UseMI : *MBB) {
831 // Collect all data dependencies.
834 getPHIDeps(&UseMI, Deps, TBI.Pred, MTM.MRI);
835 else if (getDataDeps(&UseMI, Deps, MTM.MRI))
836 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
838 // Filter and process dependencies, computing the earliest issue cycle.
840 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
841 const DataDep &Dep = Deps[i];
842 const TraceBlockInfo&DepTBI =
843 BlockInfo[Dep.DefMI->getParent()->getNumber()];
844 // Ignore dependencies from outside the current trace.
845 if (!DepTBI.isUsefulDominator(TBI))
847 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
848 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
849 // Add latency if DefMI is a real instruction. Transients get latency 0.
850 if (!Dep.DefMI->isTransient())
851 DepCycle += MTM.SchedModel
852 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
853 Cycle = std::max(Cycle, DepCycle);
855 // Remember the instruction depth.
856 InstrCycles &MICycles = Cycles[&UseMI];
857 MICycles.Depth = Cycle;
859 if (!TBI.HasValidInstrHeights) {
860 DEBUG(dbgs() << Cycle << '\t' << UseMI);
863 // Update critical path length.
864 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
865 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
870 // Identify physreg dependencies for MI when scanning instructions upwards.
871 // Return the issue height of MI after considering any live regunits.
872 // Height is the issue height computed from virtual register dependencies alone.
873 static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
874 SparseSet<LiveRegUnit> &RegUnits,
875 const TargetSchedModel &SchedModel,
876 const TargetInstrInfo *TII,
877 const TargetRegisterInfo *TRI) {
878 SmallVector<unsigned, 8> ReadOps;
879 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
882 unsigned Reg = MO->getReg();
883 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
886 ReadOps.push_back(MO.getOperandNo());
889 // This is a def of Reg. Remove corresponding entries from RegUnits, and
890 // update MI Height to consider the physreg dependencies.
891 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
892 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
893 if (I == RegUnits.end())
895 unsigned DepHeight = I->Cycle;
896 if (!MI->isTransient()) {
897 // We may not know the UseMI of this dependency, if it came from the
898 // live-in list. SchedModel can handle a NULL UseMI.
899 DepHeight += SchedModel
900 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op);
902 Height = std::max(Height, DepHeight);
903 // This regunit is dead above MI.
908 // Now we know the height of MI. Update any regunits read.
909 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
910 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
911 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
912 LiveRegUnit &LRU = RegUnits[*Units];
913 // Set the height to the highest reader of the unit.
914 if (LRU.Cycle <= Height && LRU.MI != MI) {
926 typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
928 // Push the height of DefMI upwards if required to match UseMI.
929 // Return true if this is the first time DefMI was seen.
930 static bool pushDepHeight(const DataDep &Dep,
931 const MachineInstr *UseMI, unsigned UseHeight,
932 MIHeightMap &Heights,
933 const TargetSchedModel &SchedModel,
934 const TargetInstrInfo *TII) {
935 // Adjust height by Dep.DefMI latency.
936 if (!Dep.DefMI->isTransient())
937 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
940 // Update Heights[DefMI] to be the maximum height seen.
941 MIHeightMap::iterator I;
943 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
947 // DefMI has been pushed before. Give it the max height.
948 if (I->second < UseHeight)
949 I->second = UseHeight;
953 /// Assuming that the virtual register defined by DefMI:DefOp was used by
954 /// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
955 /// when reaching the block that contains DefMI.
956 void MachineTraceMetrics::Ensemble::
957 addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
958 ArrayRef<const MachineBasicBlock*> Trace) {
959 assert(!Trace.empty() && "Trace should contain at least one block");
960 unsigned Reg = DefMI->getOperand(DefOp).getReg();
961 assert(TargetRegisterInfo::isVirtualRegister(Reg));
962 const MachineBasicBlock *DefMBB = DefMI->getParent();
964 // Reg is live-in to all blocks in Trace that follow DefMBB.
965 for (unsigned i = Trace.size(); i; --i) {
966 const MachineBasicBlock *MBB = Trace[i-1];
969 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
970 // Just add the register. The height will be updated later.
971 TBI.LiveIns.push_back(Reg);
975 /// Compute instruction heights in the trace through MBB. This updates MBB and
976 /// the blocks below it in the trace. It is assumed that the trace has already
978 void MachineTraceMetrics::Ensemble::
979 computeInstrHeights(const MachineBasicBlock *MBB) {
980 // The bottom of the trace may already be computed.
981 // Find the blocks that need updating.
982 SmallVector<const MachineBasicBlock*, 8> Stack;
984 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
985 assert(TBI.hasValidHeight() && "Incomplete trace");
986 if (TBI.HasValidInstrHeights)
988 Stack.push_back(MBB);
993 // As we move upwards in the trace, keep track of instructions that are
994 // required by deeper trace instructions. Map MI -> height required so far.
997 // For physregs, the def isn't known when we see the use.
998 // Instead, keep track of the highest use of each regunit.
999 SparseSet<LiveRegUnit> RegUnits;
1000 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1002 // If the bottom of the trace was already precomputed, initialize heights
1003 // from its live-in list.
1004 // MBB is the highest precomputed block in the trace.
1006 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1007 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1008 LiveInReg LI = TBI.LiveIns[i];
1009 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1010 // For virtual registers, the def latency is included.
1011 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1012 if (Height < LI.Height)
1015 // For register units, the def latency is not included because we don't
1016 // know the def yet.
1017 RegUnits[LI.Reg].Cycle = LI.Height;
1022 // Go through the trace blocks in bottom-up order.
1023 SmallVector<DataDep, 8> Deps;
1024 for (;!Stack.empty(); Stack.pop_back()) {
1026 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1027 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1028 TBI.HasValidInstrHeights = true;
1029 TBI.CriticalPath = 0;
1032 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1033 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1034 for (unsigned K = 0; K != PRHeights.size(); ++K)
1036 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1037 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1038 << MTM.SchedModel.getProcResource(K)->Name << " ("
1039 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1043 // Get dependencies from PHIs in the trace successor.
1044 const MachineBasicBlock *Succ = TBI.Succ;
1045 // If MBB is the last block in the trace, and it has a back-edge to the
1046 // loop header, get loop-carried dependencies from PHIs in the header. For
1047 // that purpose, pretend that all the loop header PHIs have height 0.
1049 if (const MachineLoop *Loop = getLoopFor(MBB))
1050 if (MBB->isSuccessor(Loop->getHeader()))
1051 Succ = Loop->getHeader();
1054 for (const auto &PHI : *Succ) {
1058 getPHIDeps(&PHI, Deps, MBB, MTM.MRI);
1059 if (!Deps.empty()) {
1060 // Loop header PHI heights are all 0.
1061 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1062 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
1063 if (pushDepHeight(Deps.front(), &PHI, Height,
1064 Heights, MTM.SchedModel, MTM.TII))
1065 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
1070 // Go through the block backwards.
1071 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1073 const MachineInstr *MI = --BI;
1075 // Find the MI height as determined by virtual register uses in the
1078 MIHeightMap::iterator HeightI = Heights.find(MI);
1079 if (HeightI != Heights.end()) {
1080 Cycle = HeightI->second;
1081 // We won't be seeing any more MI uses.
1082 Heights.erase(HeightI);
1085 // Don't process PHI deps. They depend on the specific predecessor, and
1086 // we'll get them when visiting the predecessor.
1088 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1090 // There may also be regunit dependencies to include in the height.
1092 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
1093 MTM.SchedModel, MTM.TII, MTM.TRI);
1095 // Update the required height of any virtual registers read by MI.
1096 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
1097 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
1098 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
1100 InstrCycles &MICycles = Cycles[MI];
1101 MICycles.Height = Cycle;
1102 if (!TBI.HasValidInstrDepths) {
1103 DEBUG(dbgs() << Cycle << '\t' << *MI);
1106 // Update critical path length.
1107 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1108 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
1111 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1112 // height because the final height isn't known until now.
1113 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
1114 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1115 LiveInReg &LIR = TBI.LiveIns[i];
1116 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1117 LIR.Height = Heights.lookup(DefMI);
1118 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1121 // Transfer the live regunits to the live-in list.
1122 for (SparseSet<LiveRegUnit>::const_iterator
1123 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1124 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1125 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1126 << '@' << RI->Cycle);
1128 DEBUG(dbgs() << '\n');
1130 if (!TBI.HasValidInstrDepths)
1132 // Add live-ins to the critical path length.
1133 TBI.CriticalPath = std::max(TBI.CriticalPath,
1134 computeCrossBlockCriticalPath(TBI));
1135 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
1139 MachineTraceMetrics::Trace
1140 MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1141 // FIXME: Check cache tags, recompute as needed.
1143 computeInstrDepths(MBB);
1144 computeInstrHeights(MBB);
1145 return Trace(*this, BlockInfo[MBB->getNumber()]);
1149 MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1150 assert(MI && "Not an instruction.");
1151 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1152 "MI must be in the trace center block");
1153 InstrCycles Cyc = getInstrCycles(MI);
1154 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1158 MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1159 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1160 SmallVector<DataDep, 1> Deps;
1161 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1162 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1163 DataDep &Dep = Deps.front();
1164 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1165 // Add latency if DefMI is a real instruction. Transients get latency 0.
1166 if (!Dep.DefMI->isTransient())
1167 DepCycle += TE.MTM.SchedModel
1168 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp);
1172 /// When bottom is set include instructions in current block in estimate.
1173 unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
1174 // Find the limiting processor resource.
1175 // Numbers have been pre-scaled to be comparable.
1177 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1179 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1180 for (unsigned K = 0; K != PRDepths.size(); ++K)
1181 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1183 for (unsigned K = 0; K != PRDepths.size(); ++K)
1184 PRMax = std::max(PRMax, PRDepths[K]);
1186 // Convert to cycle count.
1187 PRMax = TE.MTM.getCycles(PRMax);
1189 /// All instructions before current block
1190 unsigned Instrs = TBI.InstrDepth;
1191 // plus instructions in current block
1193 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
1194 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1196 // Assume issue width 1 without a schedule model.
1197 return std::max(Instrs, PRMax);
1200 unsigned MachineTraceMetrics::Trace::getResourceLength(
1201 ArrayRef<const MachineBasicBlock *> Extrablocks,
1202 ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1203 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
1204 // Add up resources above and below the center block.
1205 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1206 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1209 // Capture computing cycles from extra instructions
1210 auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
1211 unsigned ResourceIdx)
1213 unsigned Cycles = 0;
1214 for (unsigned I = 0; I != Instrs.size(); ++I) {
1215 const MCSchedClassDesc *SC = Instrs[I];
1218 for (TargetSchedModel::ProcResIter
1219 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1220 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
1222 if (PI->ProcResourceIdx != ResourceIdx)
1225 (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
1231 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1232 unsigned PRCycles = PRDepths[K] + PRHeights[K];
1233 for (unsigned I = 0; I != Extrablocks.size(); ++I)
1234 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
1235 PRCycles += extraCycles(ExtraInstrs, K);
1236 PRCycles -= extraCycles(RemoveInstrs, K);
1237 PRMax = std::max(PRMax, PRCycles);
1239 // Convert to cycle count.
1240 PRMax = TE.MTM.getCycles(PRMax);
1242 // Instrs: #instructions in current trace outside current block.
1243 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1244 // Add instruction count from the extra blocks.
1245 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1246 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
1247 Instrs += ExtraInstrs.size();
1248 Instrs -= RemoveInstrs.size();
1249 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1251 // Assume issue width 1 without a schedule model.
1252 return std::max(Instrs, PRMax);
1255 bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr *DefMI,
1256 const MachineInstr *UseMI) const {
1257 if (DefMI->getParent() == UseMI->getParent())
1260 const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI->getParent()->getNumber()];
1261 const TraceBlockInfo &TBI = TE.BlockInfo[UseMI->getParent()->getNumber()];
1263 return DepTBI.isUsefulDominator(TBI);
1266 void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1267 OS << getName() << " ensemble:\n";
1268 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1269 OS << " BB#" << i << '\t';
1270 BlockInfo[i].print(OS);
1275 void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1276 if (hasValidDepth()) {
1277 OS << "depth=" << InstrDepth;
1279 OS << " pred=BB#" << Pred->getNumber();
1282 OS << " head=BB#" << Head;
1283 if (HasValidInstrDepths)
1286 OS << "depth invalid";
1288 if (hasValidHeight()) {
1289 OS << "height=" << InstrHeight;
1291 OS << " succ=BB#" << Succ->getNumber();
1294 OS << " tail=BB#" << Tail;
1295 if (HasValidInstrHeights)
1298 OS << "height invalid";
1299 if (HasValidInstrDepths && HasValidInstrHeights)
1300 OS << ", crit=" << CriticalPath;
1303 void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
1304 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1306 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1307 << " --> BB#" << TBI.Tail << ':';
1308 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1309 OS << ' ' << getInstrCount() << " instrs.";
1310 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1311 OS << ' ' << TBI.CriticalPath << " cycles.";
1313 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
1314 OS << "\nBB#" << MBBNum;
1315 while (Block->hasValidDepth() && Block->Pred) {
1316 unsigned Num = Block->Pred->getNumber();
1317 OS << " <- BB#" << Num;
1318 Block = &TE.BlockInfo[Num];
1323 while (Block->hasValidHeight() && Block->Succ) {
1324 unsigned Num = Block->Succ->getNumber();
1325 OS << " -> BB#" << Num;
1326 Block = &TE.BlockInfo[Num];