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->getTarget().getInstrInfo();
56 TRI = MF->getTarget().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 (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
102 const MachineInstr *MI = I;
103 if (MI->isTransient())
107 FBI->HasCalls = true;
109 // Count processor resources used.
110 if (!SchedModel.hasInstrSchedModel())
112 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(MI);
116 for (TargetSchedModel::ProcResIter
117 PI = SchedModel.getWriteProcResBegin(SC),
118 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
119 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
120 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
123 FBI->InstrCount = InstrCount;
125 // Scale the resource cycles so they are comparable.
126 unsigned PROffset = MBB->getNumber() * PRKinds;
127 for (unsigned K = 0; K != PRKinds; ++K)
128 ProcResourceCycles[PROffset + K] =
129 PRCycles[K] * SchedModel.getResourceFactor(K);
135 MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
136 assert(BlockInfo[MBBNum].hasResources() &&
137 "getResources() must be called before getProcResourceCycles()");
138 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
139 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
140 return ArrayRef<unsigned>(ProcResourceCycles.data() + MBBNum * PRKinds,
145 //===----------------------------------------------------------------------===//
146 // Ensemble utility functions
147 //===----------------------------------------------------------------------===//
149 MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
151 BlockInfo.resize(MTM.BlockInfo.size());
152 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
153 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
154 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
157 // Virtual destructor serves as an anchor.
158 MachineTraceMetrics::Ensemble::~Ensemble() {}
161 MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
162 return MTM.Loops->getLoopFor(MBB);
165 // Update resource-related information in the TraceBlockInfo for MBB.
166 // Only update resources related to the trace above MBB.
167 void MachineTraceMetrics::Ensemble::
168 computeDepthResources(const MachineBasicBlock *MBB) {
169 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
170 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
171 unsigned PROffset = MBB->getNumber() * PRKinds;
173 // Compute resources from trace above. The top block is simple.
176 TBI->Head = MBB->getNumber();
177 std::fill(ProcResourceDepths.begin() + PROffset,
178 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
182 // Compute from the block above. A post-order traversal ensures the
183 // predecessor is always computed first.
184 unsigned PredNum = TBI->Pred->getNumber();
185 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
186 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
187 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
188 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
189 TBI->Head = PredTBI->Head;
191 // Compute per-resource depths.
192 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
193 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
194 for (unsigned K = 0; K != PRKinds; ++K)
195 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
198 // Update resource-related information in the TraceBlockInfo for MBB.
199 // Only update resources related to the trace below MBB.
200 void MachineTraceMetrics::Ensemble::
201 computeHeightResources(const MachineBasicBlock *MBB) {
202 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
203 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
204 unsigned PROffset = MBB->getNumber() * PRKinds;
206 // Compute resources for the current block.
207 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
208 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
210 // The trace tail is done.
212 TBI->Tail = MBB->getNumber();
213 std::copy(PRCycles.begin(), PRCycles.end(),
214 ProcResourceHeights.begin() + PROffset);
218 // Compute from the block below. A post-order traversal ensures the
219 // predecessor is always computed first.
220 unsigned SuccNum = TBI->Succ->getNumber();
221 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
222 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
223 TBI->InstrHeight += SuccTBI->InstrHeight;
224 TBI->Tail = SuccTBI->Tail;
226 // Compute per-resource heights.
227 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
228 for (unsigned K = 0; K != PRKinds; ++K)
229 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
232 // Check if depth resources for MBB are valid and return the TBI.
233 // Return NULL if the resources have been invalidated.
234 const MachineTraceMetrics::TraceBlockInfo*
235 MachineTraceMetrics::Ensemble::
236 getDepthResources(const MachineBasicBlock *MBB) const {
237 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
238 return TBI->hasValidDepth() ? TBI : nullptr;
241 // Check if height resources for MBB are valid and return the TBI.
242 // Return NULL if the resources have been invalidated.
243 const MachineTraceMetrics::TraceBlockInfo*
244 MachineTraceMetrics::Ensemble::
245 getHeightResources(const MachineBasicBlock *MBB) const {
246 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
247 return TBI->hasValidHeight() ? TBI : nullptr;
250 /// Get an array of processor resource depths for MBB. Indexed by processor
251 /// resource kind, this array contains the scaled processor resources consumed
252 /// by all blocks preceding MBB in its trace. It does not include instructions
255 /// Compare TraceBlockInfo::InstrDepth.
257 MachineTraceMetrics::Ensemble::
258 getProcResourceDepths(unsigned MBBNum) const {
259 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
260 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
261 return ArrayRef<unsigned>(ProcResourceDepths.data() + MBBNum * PRKinds,
265 /// Get an array of processor resource heights for MBB. Indexed by processor
266 /// resource kind, this array contains the scaled processor resources consumed
267 /// by this block and all blocks following it in its trace.
269 /// Compare TraceBlockInfo::InstrHeight.
271 MachineTraceMetrics::Ensemble::
272 getProcResourceHeights(unsigned MBBNum) const {
273 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
274 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
275 return ArrayRef<unsigned>(ProcResourceHeights.data() + MBBNum * PRKinds,
279 //===----------------------------------------------------------------------===//
280 // Trace Selection Strategies
281 //===----------------------------------------------------------------------===//
283 // A trace selection strategy is implemented as a sub-class of Ensemble. The
284 // trace through a block B is computed by two DFS traversals of the CFG
285 // starting from B. One upwards, and one downwards. During the upwards DFS,
286 // pickTracePred() is called on the post-ordered blocks. During the downwards
287 // DFS, pickTraceSucc() is called in a post-order.
290 // We never allow traces that leave loops, but we do allow traces to enter
291 // nested loops. We also never allow traces to contain back-edges.
293 // This means that a loop header can never appear above the center block of a
294 // trace, except as the trace head. Below the center block, loop exiting edges
297 // Return true if an edge from the From loop to the To loop is leaving a loop.
298 // Either of To and From can be null.
299 static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
300 return From && !From->contains(To);
303 // MinInstrCountEnsemble - Pick the trace that executes the least number of
306 class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
307 const char *getName() const override { return "MinInstr"; }
308 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
309 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
312 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
313 : MachineTraceMetrics::Ensemble(mtm) {}
317 // Select the preferred predecessor for MBB.
318 const MachineBasicBlock*
319 MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
320 if (MBB->pred_empty())
322 const MachineLoop *CurLoop = getLoopFor(MBB);
323 // Don't leave loops, and never follow back-edges.
324 if (CurLoop && MBB == CurLoop->getHeader())
326 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
327 const MachineBasicBlock *Best = nullptr;
328 unsigned BestDepth = 0;
329 for (MachineBasicBlock::const_pred_iterator
330 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
331 const MachineBasicBlock *Pred = *I;
332 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
333 getDepthResources(Pred);
334 // Ignore cycles that aren't natural loops.
337 // Pick the predecessor that would give this block the smallest InstrDepth.
338 unsigned Depth = PredTBI->InstrDepth + CurCount;
339 if (!Best || Depth < BestDepth)
340 Best = Pred, BestDepth = Depth;
345 // Select the preferred successor for MBB.
346 const MachineBasicBlock*
347 MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
348 if (MBB->pred_empty())
350 const MachineLoop *CurLoop = getLoopFor(MBB);
351 const MachineBasicBlock *Best = nullptr;
352 unsigned BestHeight = 0;
353 for (MachineBasicBlock::const_succ_iterator
354 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
355 const MachineBasicBlock *Succ = *I;
356 // Don't consider back-edges.
357 if (CurLoop && Succ == CurLoop->getHeader())
359 // Don't consider successors exiting CurLoop.
360 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
362 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
363 getHeightResources(Succ);
364 // Ignore cycles that aren't natural loops.
367 // Pick the successor that would give this block the smallest InstrHeight.
368 unsigned Height = SuccTBI->InstrHeight;
369 if (!Best || Height < BestHeight)
370 Best = Succ, BestHeight = Height;
375 // Get an Ensemble sub-class for the requested trace strategy.
376 MachineTraceMetrics::Ensemble *
377 MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
378 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
379 Ensemble *&E = Ensembles[strategy];
383 // Allocate new Ensemble on demand.
385 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
386 default: llvm_unreachable("Invalid trace strategy enum");
390 void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
391 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
392 BlockInfo[MBB->getNumber()].invalidate();
393 for (unsigned i = 0; i != TS_NumStrategies; ++i)
395 Ensembles[i]->invalidate(MBB);
398 void MachineTraceMetrics::verifyAnalysis() const {
402 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
403 for (unsigned i = 0; i != TS_NumStrategies; ++i)
405 Ensembles[i]->verify();
409 //===----------------------------------------------------------------------===//
411 //===----------------------------------------------------------------------===//
413 // Traces are built by two CFG traversals. To avoid recomputing too much, use a
414 // set abstraction that confines the search to the current loop, and doesn't
419 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
420 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
421 const MachineLoopInfo *Loops;
423 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
424 const MachineLoopInfo *loops)
425 : Blocks(blocks), Loops(loops), Downward(false) {}
429 // Specialize po_iterator_storage in order to prune the post-order traversal so
430 // it is limited to the current loop and doesn't traverse the loop back edges.
433 class po_iterator_storage<LoopBounds, true> {
436 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
437 void finishPostorder(const MachineBasicBlock*) {}
439 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
440 // Skip already visited To blocks.
441 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
442 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
444 // From is null once when To is the trace center block.
446 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
447 // Don't follow backedges, don't leave FromLoop when going upwards.
448 if ((LB.Downward ? To : From) == FromLoop->getHeader())
450 // Don't leave FromLoop.
451 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
455 // To is a new block. Mark the block as visited in case the CFG has cycles
456 // that MachineLoopInfo didn't recognize as a natural loop.
457 return LB.Visited.insert(To);
462 /// Compute the trace through MBB.
463 void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
464 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
465 << MBB->getNumber() << '\n');
466 // Set up loop bounds for the backwards post-order traversal.
467 LoopBounds Bounds(BlockInfo, MTM.Loops);
469 // Run an upwards post-order search for the trace start.
470 Bounds.Downward = false;
471 Bounds.Visited.clear();
472 typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
473 for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
475 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
476 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
477 // All the predecessors have been visited, pick the preferred one.
478 TBI.Pred = pickTracePred(*I);
481 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
485 // The trace leading to I is now known, compute the depth resources.
486 computeDepthResources(*I);
489 // Run a downwards post-order search for the trace end.
490 Bounds.Downward = true;
491 Bounds.Visited.clear();
492 typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
493 for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
495 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
496 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
497 // All the successors have been visited, pick the preferred one.
498 TBI.Succ = pickTraceSucc(*I);
501 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
505 // The trace leaving I is now known, compute the height resources.
506 computeHeightResources(*I);
510 /// Invalidate traces through BadMBB.
512 MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
513 SmallVector<const MachineBasicBlock*, 16> WorkList;
514 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
516 // Invalidate height resources of blocks above MBB.
517 if (BadTBI.hasValidHeight()) {
518 BadTBI.invalidateHeight();
519 WorkList.push_back(BadMBB);
521 const MachineBasicBlock *MBB = WorkList.pop_back_val();
522 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
524 // Find any MBB predecessors that have MBB as their preferred successor.
525 // They are the only ones that need to be invalidated.
526 for (MachineBasicBlock::const_pred_iterator
527 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
528 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
529 if (!TBI.hasValidHeight())
531 if (TBI.Succ == MBB) {
532 TBI.invalidateHeight();
533 WorkList.push_back(*I);
536 // Verify that TBI.Succ is actually a *I successor.
537 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
539 } while (!WorkList.empty());
542 // Invalidate depth resources of blocks below MBB.
543 if (BadTBI.hasValidDepth()) {
544 BadTBI.invalidateDepth();
545 WorkList.push_back(BadMBB);
547 const MachineBasicBlock *MBB = WorkList.pop_back_val();
548 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
550 // Find any MBB successors that have MBB as their preferred predecessor.
551 // They are the only ones that need to be invalidated.
552 for (MachineBasicBlock::const_succ_iterator
553 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
554 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
555 if (!TBI.hasValidDepth())
557 if (TBI.Pred == MBB) {
558 TBI.invalidateDepth();
559 WorkList.push_back(*I);
562 // Verify that TBI.Pred is actually a *I predecessor.
563 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
565 } while (!WorkList.empty());
568 // Clear any per-instruction data. We only have to do this for BadMBB itself
569 // because the instructions in that block may change. Other blocks may be
570 // invalidated, but their instructions will stay the same, so there is no
571 // need to erase the Cycle entries. They will be overwritten when we
573 for (MachineBasicBlock::const_iterator I = BadMBB->begin(), E = BadMBB->end();
578 void MachineTraceMetrics::Ensemble::verify() const {
580 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
581 "Outdated BlockInfo size");
582 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
583 const TraceBlockInfo &TBI = BlockInfo[Num];
584 if (TBI.hasValidDepth() && TBI.Pred) {
585 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
586 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
587 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
588 "Trace is broken, depth should have been invalidated.");
589 const MachineLoop *Loop = getLoopFor(MBB);
590 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
592 if (TBI.hasValidHeight() && TBI.Succ) {
593 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
594 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
595 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
596 "Trace is broken, height should have been invalidated.");
597 const MachineLoop *Loop = getLoopFor(MBB);
598 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
599 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
600 "Trace contains backedge");
606 //===----------------------------------------------------------------------===//
608 //===----------------------------------------------------------------------===//
610 // Compute the depth and height of each instruction based on data dependencies
611 // and instruction latencies. These cycle numbers assume that the CPU can issue
612 // an infinite number of instructions per cycle as long as their dependencies
615 // A data dependency is represented as a defining MI and operand numbers on the
616 // defining and using MI.
619 const MachineInstr *DefMI;
623 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
624 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
626 /// Create a DataDep from an SSA form virtual register.
627 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
629 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
630 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
631 assert(!DefI.atEnd() && "Register has no defs");
632 DefMI = DefI->getParent();
633 DefOp = DefI.getOperandNo();
634 assert((++DefI).atEnd() && "Register has multiple defs");
639 // Get the input data dependencies that must be ready before UseMI can issue.
640 // Return true if UseMI has any physreg operands.
641 static bool getDataDeps(const MachineInstr *UseMI,
642 SmallVectorImpl<DataDep> &Deps,
643 const MachineRegisterInfo *MRI) {
644 bool HasPhysRegs = false;
645 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
648 unsigned Reg = MO->getReg();
651 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
655 // Collect virtual register reads.
657 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
662 // Get the input data dependencies of a PHI instruction, using Pred as the
663 // preferred predecessor.
664 // This will add at most one dependency to Deps.
665 static void getPHIDeps(const MachineInstr *UseMI,
666 SmallVectorImpl<DataDep> &Deps,
667 const MachineBasicBlock *Pred,
668 const MachineRegisterInfo *MRI) {
669 // No predecessor at the beginning of a trace. Ignore dependencies.
672 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
673 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
674 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
675 unsigned Reg = UseMI->getOperand(i).getReg();
676 Deps.push_back(DataDep(MRI, Reg, i));
682 // Keep track of physreg data dependencies by recording each live register unit.
683 // Associate each regunit with an instruction operand. Depending on the
684 // direction instructions are scanned, it could be the operand that defined the
685 // regunit, or the highest operand to read the regunit.
690 const MachineInstr *MI;
693 unsigned getSparseSetIndex() const { return RegUnit; }
695 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {}
699 // Identify physreg dependencies for UseMI, and update the live regunit
700 // tracking set when scanning instructions downwards.
701 static void updatePhysDepsDownwards(const MachineInstr *UseMI,
702 SmallVectorImpl<DataDep> &Deps,
703 SparseSet<LiveRegUnit> &RegUnits,
704 const TargetRegisterInfo *TRI) {
705 SmallVector<unsigned, 8> Kills;
706 SmallVector<unsigned, 8> LiveDefOps;
708 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
711 unsigned Reg = MO->getReg();
712 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
714 // Track live defs and kills for updating RegUnits.
717 Kills.push_back(Reg);
719 LiveDefOps.push_back(MO.getOperandNo());
720 } else if (MO->isKill())
721 Kills.push_back(Reg);
722 // Identify dependencies.
725 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
726 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
727 if (I == RegUnits.end())
729 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
734 // Update RegUnits to reflect live registers after UseMI.
736 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
737 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
738 RegUnits.erase(*Units);
740 // Second, live defs.
741 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
742 unsigned DefOp = LiveDefOps[i];
743 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
744 Units.isValid(); ++Units) {
745 LiveRegUnit &LRU = RegUnits[*Units];
752 /// The length of the critical path through a trace is the maximum of two path
755 /// 1. The maximum height+depth over all instructions in the trace center block.
757 /// 2. The longest cross-block dependency chain. For small blocks, it is
758 /// possible that the critical path through the trace doesn't include any
759 /// instructions in the block.
761 /// This function computes the second number from the live-in list of the
763 unsigned MachineTraceMetrics::Ensemble::
764 computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
765 assert(TBI.HasValidInstrDepths && "Missing depth info");
766 assert(TBI.HasValidInstrHeights && "Missing height info");
768 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
769 const LiveInReg &LIR = TBI.LiveIns[i];
770 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
772 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
773 // Ignore dependencies outside the current trace.
774 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
775 if (!DefTBI.isUsefulDominator(TBI))
777 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
778 MaxLen = std::max(MaxLen, Len);
783 /// Compute instruction depths for all instructions above or in MBB in its
784 /// trace. This assumes that the trace through MBB has already been computed.
785 void MachineTraceMetrics::Ensemble::
786 computeInstrDepths(const MachineBasicBlock *MBB) {
787 // The top of the trace may already be computed, and HasValidInstrDepths
788 // implies Head->HasValidInstrDepths, so we only need to start from the first
789 // block in the trace that needs to be recomputed.
790 SmallVector<const MachineBasicBlock*, 8> Stack;
792 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
793 assert(TBI.hasValidDepth() && "Incomplete trace");
794 if (TBI.HasValidInstrDepths)
796 Stack.push_back(MBB);
800 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
801 // in the trace. We should track any live-out physregs that were defined in
802 // the trace. This is quite rare in SSA form, typically created by CSE
803 // hoisting a compare.
804 SparseSet<LiveRegUnit> RegUnits;
805 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
807 // Go through trace blocks in top-down order, stopping after the center block.
808 SmallVector<DataDep, 8> Deps;
809 while (!Stack.empty()) {
810 MBB = Stack.pop_back_val();
811 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
812 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
813 TBI.HasValidInstrDepths = true;
814 TBI.CriticalPath = 0;
816 // Print out resource depths here as well.
818 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
819 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
820 for (unsigned K = 0; K != PRDepths.size(); ++K)
822 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
823 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
824 << MTM.SchedModel.getProcResource(K)->Name << " ("
825 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
829 // Also compute the critical path length through MBB when possible.
830 if (TBI.HasValidInstrHeights)
831 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
833 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
835 const MachineInstr *UseMI = I;
837 // Collect all data dependencies.
840 getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
841 else if (getDataDeps(UseMI, Deps, MTM.MRI))
842 updatePhysDepsDownwards(UseMI, Deps, RegUnits, MTM.TRI);
844 // Filter and process dependencies, computing the earliest issue cycle.
846 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
847 const DataDep &Dep = Deps[i];
848 const TraceBlockInfo&DepTBI =
849 BlockInfo[Dep.DefMI->getParent()->getNumber()];
850 // Ignore dependencies from outside the current trace.
851 if (!DepTBI.isUsefulDominator(TBI))
853 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
854 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
855 // Add latency if DefMI is a real instruction. Transients get latency 0.
856 if (!Dep.DefMI->isTransient())
857 DepCycle += MTM.SchedModel
858 .computeOperandLatency(Dep.DefMI, Dep.DefOp, UseMI, Dep.UseOp);
859 Cycle = std::max(Cycle, DepCycle);
861 // Remember the instruction depth.
862 InstrCycles &MICycles = Cycles[UseMI];
863 MICycles.Depth = Cycle;
865 if (!TBI.HasValidInstrHeights) {
866 DEBUG(dbgs() << Cycle << '\t' << *UseMI);
869 // Update critical path length.
870 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
871 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *UseMI);
876 // Identify physreg dependencies for MI when scanning instructions upwards.
877 // Return the issue height of MI after considering any live regunits.
878 // Height is the issue height computed from virtual register dependencies alone.
879 static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
880 SparseSet<LiveRegUnit> &RegUnits,
881 const TargetSchedModel &SchedModel,
882 const TargetInstrInfo *TII,
883 const TargetRegisterInfo *TRI) {
884 SmallVector<unsigned, 8> ReadOps;
885 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
888 unsigned Reg = MO->getReg();
889 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
892 ReadOps.push_back(MO.getOperandNo());
895 // This is a def of Reg. Remove corresponding entries from RegUnits, and
896 // update MI Height to consider the physreg dependencies.
897 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
898 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
899 if (I == RegUnits.end())
901 unsigned DepHeight = I->Cycle;
902 if (!MI->isTransient()) {
903 // We may not know the UseMI of this dependency, if it came from the
904 // live-in list. SchedModel can handle a NULL UseMI.
905 DepHeight += SchedModel
906 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op);
908 Height = std::max(Height, DepHeight);
909 // This regunit is dead above MI.
914 // Now we know the height of MI. Update any regunits read.
915 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
916 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
917 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
918 LiveRegUnit &LRU = RegUnits[*Units];
919 // Set the height to the highest reader of the unit.
920 if (LRU.Cycle <= Height && LRU.MI != MI) {
932 typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
934 // Push the height of DefMI upwards if required to match UseMI.
935 // Return true if this is the first time DefMI was seen.
936 static bool pushDepHeight(const DataDep &Dep,
937 const MachineInstr *UseMI, unsigned UseHeight,
938 MIHeightMap &Heights,
939 const TargetSchedModel &SchedModel,
940 const TargetInstrInfo *TII) {
941 // Adjust height by Dep.DefMI latency.
942 if (!Dep.DefMI->isTransient())
943 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
946 // Update Heights[DefMI] to be the maximum height seen.
947 MIHeightMap::iterator I;
949 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
953 // DefMI has been pushed before. Give it the max height.
954 if (I->second < UseHeight)
955 I->second = UseHeight;
959 /// Assuming that the virtual register defined by DefMI:DefOp was used by
960 /// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
961 /// when reaching the block that contains DefMI.
962 void MachineTraceMetrics::Ensemble::
963 addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
964 ArrayRef<const MachineBasicBlock*> Trace) {
965 assert(!Trace.empty() && "Trace should contain at least one block");
966 unsigned Reg = DefMI->getOperand(DefOp).getReg();
967 assert(TargetRegisterInfo::isVirtualRegister(Reg));
968 const MachineBasicBlock *DefMBB = DefMI->getParent();
970 // Reg is live-in to all blocks in Trace that follow DefMBB.
971 for (unsigned i = Trace.size(); i; --i) {
972 const MachineBasicBlock *MBB = Trace[i-1];
975 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
976 // Just add the register. The height will be updated later.
977 TBI.LiveIns.push_back(Reg);
981 /// Compute instruction heights in the trace through MBB. This updates MBB and
982 /// the blocks below it in the trace. It is assumed that the trace has already
984 void MachineTraceMetrics::Ensemble::
985 computeInstrHeights(const MachineBasicBlock *MBB) {
986 // The bottom of the trace may already be computed.
987 // Find the blocks that need updating.
988 SmallVector<const MachineBasicBlock*, 8> Stack;
990 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
991 assert(TBI.hasValidHeight() && "Incomplete trace");
992 if (TBI.HasValidInstrHeights)
994 Stack.push_back(MBB);
999 // As we move upwards in the trace, keep track of instructions that are
1000 // required by deeper trace instructions. Map MI -> height required so far.
1001 MIHeightMap Heights;
1003 // For physregs, the def isn't known when we see the use.
1004 // Instead, keep track of the highest use of each regunit.
1005 SparseSet<LiveRegUnit> RegUnits;
1006 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1008 // If the bottom of the trace was already precomputed, initialize heights
1009 // from its live-in list.
1010 // MBB is the highest precomputed block in the trace.
1012 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1013 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1014 LiveInReg LI = TBI.LiveIns[i];
1015 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1016 // For virtual registers, the def latency is included.
1017 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1018 if (Height < LI.Height)
1021 // For register units, the def latency is not included because we don't
1022 // know the def yet.
1023 RegUnits[LI.Reg].Cycle = LI.Height;
1028 // Go through the trace blocks in bottom-up order.
1029 SmallVector<DataDep, 8> Deps;
1030 for (;!Stack.empty(); Stack.pop_back()) {
1032 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1033 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1034 TBI.HasValidInstrHeights = true;
1035 TBI.CriticalPath = 0;
1038 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1039 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1040 for (unsigned K = 0; K != PRHeights.size(); ++K)
1042 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1043 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1044 << MTM.SchedModel.getProcResource(K)->Name << " ("
1045 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1049 // Get dependencies from PHIs in the trace successor.
1050 const MachineBasicBlock *Succ = TBI.Succ;
1051 // If MBB is the last block in the trace, and it has a back-edge to the
1052 // loop header, get loop-carried dependencies from PHIs in the header. For
1053 // that purpose, pretend that all the loop header PHIs have height 0.
1055 if (const MachineLoop *Loop = getLoopFor(MBB))
1056 if (MBB->isSuccessor(Loop->getHeader()))
1057 Succ = Loop->getHeader();
1060 for (MachineBasicBlock::const_iterator I = Succ->begin(), E = Succ->end();
1061 I != E && I->isPHI(); ++I) {
1062 const MachineInstr *PHI = I;
1064 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
1065 if (!Deps.empty()) {
1066 // Loop header PHI heights are all 0.
1067 unsigned Height = TBI.Succ ? Cycles.lookup(PHI).Height : 0;
1068 DEBUG(dbgs() << "pred\t" << Height << '\t' << *PHI);
1069 if (pushDepHeight(Deps.front(), PHI, Height,
1070 Heights, MTM.SchedModel, MTM.TII))
1071 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
1076 // Go through the block backwards.
1077 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1079 const MachineInstr *MI = --BI;
1081 // Find the MI height as determined by virtual register uses in the
1084 MIHeightMap::iterator HeightI = Heights.find(MI);
1085 if (HeightI != Heights.end()) {
1086 Cycle = HeightI->second;
1087 // We won't be seeing any more MI uses.
1088 Heights.erase(HeightI);
1091 // Don't process PHI deps. They depend on the specific predecessor, and
1092 // we'll get them when visiting the predecessor.
1094 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1096 // There may also be regunit dependencies to include in the height.
1098 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
1099 MTM.SchedModel, MTM.TII, MTM.TRI);
1101 // Update the required height of any virtual registers read by MI.
1102 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
1103 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
1104 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
1106 InstrCycles &MICycles = Cycles[MI];
1107 MICycles.Height = Cycle;
1108 if (!TBI.HasValidInstrDepths) {
1109 DEBUG(dbgs() << Cycle << '\t' << *MI);
1112 // Update critical path length.
1113 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1114 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
1117 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1118 // height because the final height isn't known until now.
1119 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
1120 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1121 LiveInReg &LIR = TBI.LiveIns[i];
1122 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1123 LIR.Height = Heights.lookup(DefMI);
1124 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1127 // Transfer the live regunits to the live-in list.
1128 for (SparseSet<LiveRegUnit>::const_iterator
1129 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1130 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1131 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1132 << '@' << RI->Cycle);
1134 DEBUG(dbgs() << '\n');
1136 if (!TBI.HasValidInstrDepths)
1138 // Add live-ins to the critical path length.
1139 TBI.CriticalPath = std::max(TBI.CriticalPath,
1140 computeCrossBlockCriticalPath(TBI));
1141 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
1145 MachineTraceMetrics::Trace
1146 MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1147 // FIXME: Check cache tags, recompute as needed.
1149 computeInstrDepths(MBB);
1150 computeInstrHeights(MBB);
1151 return Trace(*this, BlockInfo[MBB->getNumber()]);
1155 MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1156 assert(MI && "Not an instruction.");
1157 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1158 "MI must be in the trace center block");
1159 InstrCycles Cyc = getInstrCycles(MI);
1160 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1164 MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1165 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1166 SmallVector<DataDep, 1> Deps;
1167 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1168 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1169 DataDep &Dep = Deps.front();
1170 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1171 // Add latency if DefMI is a real instruction. Transients get latency 0.
1172 if (!Dep.DefMI->isTransient())
1173 DepCycle += TE.MTM.SchedModel
1174 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp);
1178 unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
1179 // Find the limiting processor resource.
1180 // Numbers have been pre-scaled to be comparable.
1182 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1184 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1185 for (unsigned K = 0; K != PRDepths.size(); ++K)
1186 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1188 for (unsigned K = 0; K != PRDepths.size(); ++K)
1189 PRMax = std::max(PRMax, PRDepths[K]);
1191 // Convert to cycle count.
1192 PRMax = TE.MTM.getCycles(PRMax);
1194 unsigned Instrs = TBI.InstrDepth;
1196 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
1197 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1199 // Assume issue width 1 without a schedule model.
1200 return std::max(Instrs, PRMax);
1204 unsigned MachineTraceMetrics::Trace::
1205 getResourceLength(ArrayRef<const MachineBasicBlock*> Extrablocks,
1206 ArrayRef<const MCSchedClassDesc*> ExtraInstrs) const {
1207 // Add up resources above and below the center block.
1208 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1209 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1211 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1212 unsigned PRCycles = PRDepths[K] + PRHeights[K];
1213 for (unsigned I = 0; I != Extrablocks.size(); ++I)
1214 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
1215 for (unsigned I = 0; I != ExtraInstrs.size(); ++I) {
1216 const MCSchedClassDesc* SC = ExtraInstrs[I];
1219 for (TargetSchedModel::ProcResIter
1220 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1221 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
1222 if (PI->ProcResourceIdx != K)
1224 PRCycles += (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(K));
1227 PRMax = std::max(PRMax, PRCycles);
1229 // Convert to cycle count.
1230 PRMax = TE.MTM.getCycles(PRMax);
1232 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1233 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1234 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
1235 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1237 // Assume issue width 1 without a schedule model.
1238 return std::max(Instrs, PRMax);
1241 void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1242 OS << getName() << " ensemble:\n";
1243 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1244 OS << " BB#" << i << '\t';
1245 BlockInfo[i].print(OS);
1250 void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1251 if (hasValidDepth()) {
1252 OS << "depth=" << InstrDepth;
1254 OS << " pred=BB#" << Pred->getNumber();
1257 OS << " head=BB#" << Head;
1258 if (HasValidInstrDepths)
1261 OS << "depth invalid";
1263 if (hasValidHeight()) {
1264 OS << "height=" << InstrHeight;
1266 OS << " succ=BB#" << Succ->getNumber();
1269 OS << " tail=BB#" << Tail;
1270 if (HasValidInstrHeights)
1273 OS << "height invalid";
1274 if (HasValidInstrDepths && HasValidInstrHeights)
1275 OS << ", crit=" << CriticalPath;
1278 void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
1279 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1281 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1282 << " --> BB#" << TBI.Tail << ':';
1283 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1284 OS << ' ' << getInstrCount() << " instrs.";
1285 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1286 OS << ' ' << TBI.CriticalPath << " cycles.";
1288 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
1289 OS << "\nBB#" << MBBNum;
1290 while (Block->hasValidDepth() && Block->Pred) {
1291 unsigned Num = Block->Pred->getNumber();
1292 OS << " <- BB#" << Num;
1293 Block = &TE.BlockInfo[Num];
1298 while (Block->hasValidHeight() && Block->Succ) {
1299 unsigned Num = Block->Succ->getNumber();
1300 OS << " -> BB#" << Num;
1301 Block = &TE.BlockInfo[Num];