blob: c154b5c9c108b29988f313a2490213106f7b759a [file] [log] [blame]
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001//===- lib/CodeGen/MachineTraceMetrics.cpp ----------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Jakob Stoklund Olesena35bf502012-08-10 22:27:29 +000010#define DEBUG_TYPE "machine-trace-metrics"
Jakob Stoklund Olesen5ed625c2013-01-17 01:06:04 +000011#include "llvm/CodeGen/MachineTraceMetrics.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000012#include "llvm/ADT/PostOrderIterator.h"
13#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000014#include "llvm/CodeGen/MachineBasicBlock.h"
15#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
16#include "llvm/CodeGen/MachineLoopInfo.h"
17#include "llvm/CodeGen/MachineRegisterInfo.h"
18#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000019#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "llvm/Support/Debug.h"
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000021#include "llvm/Support/Format.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000023#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetRegisterInfo.h"
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000025#include "llvm/Target/TargetSubtargetInfo.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000026
27using namespace llvm;
28
29char MachineTraceMetrics::ID = 0;
30char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
31
32INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
33 "machine-trace-metrics", "Machine Trace Metrics", false, true)
34INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
35INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
36INITIALIZE_PASS_END(MachineTraceMetrics,
37 "machine-trace-metrics", "Machine Trace Metrics", false, true)
38
39MachineTraceMetrics::MachineTraceMetrics()
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +000040 : MachineFunctionPass(ID), MF(0), TII(0), TRI(0), MRI(0), Loops(0) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000041 std::fill(Ensembles, array_endof(Ensembles), (Ensemble*)0);
42}
43
44void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.setPreservesAll();
46 AU.addRequired<MachineBranchProbabilityInfo>();
47 AU.addRequired<MachineLoopInfo>();
48 MachineFunctionPass::getAnalysisUsage(AU);
49}
50
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000051bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
52 MF = &Func;
53 TII = MF->getTarget().getInstrInfo();
54 TRI = MF->getTarget().getRegisterInfo();
55 MRI = &MF->getRegInfo();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000056 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000057 const TargetSubtargetInfo &ST =
58 MF->getTarget().getSubtarget<TargetSubtargetInfo>();
59 SchedModel.init(*ST.getSchedModel(), &ST, TII);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000060 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000061 ProcResourceCycles.resize(MF->getNumBlockIDs() *
62 SchedModel.getNumProcResourceKinds());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000063 return false;
64}
65
66void MachineTraceMetrics::releaseMemory() {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +000067 MF = 0;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000068 BlockInfo.clear();
69 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
70 delete Ensembles[i];
71 Ensembles[i] = 0;
72 }
73}
74
75//===----------------------------------------------------------------------===//
76// Fixed block information
77//===----------------------------------------------------------------------===//
78//
79// The number of instructions in a basic block and the CPU resources used by
80// those instructions don't depend on any given trace strategy.
81
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000082/// Compute the resource usage in basic block MBB.
83const MachineTraceMetrics::FixedBlockInfo*
84MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
85 assert(MBB && "No basic block");
86 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
87 if (FBI->hasResources())
88 return FBI;
89
90 // Compute resource usage in the block.
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000091 FBI->HasCalls = false;
92 unsigned InstrCount = 0;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000093
94 // Add up per-processor resource cycles as well.
95 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
96 SmallVector<unsigned, 32> PRCycles(PRKinds);
97
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000098 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
99 I != E; ++I) {
100 const MachineInstr *MI = I;
Jakob Stoklund Olesen3f63a582012-07-30 18:34:14 +0000101 if (MI->isTransient())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000102 continue;
103 ++InstrCount;
104 if (MI->isCall())
105 FBI->HasCalls = true;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000106
107 // Count processor resources used.
108 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(MI);
109 if (!SC->isValid())
110 continue;
111
112 for (TargetSchedModel::ProcResIter
113 PI = SchedModel.getWriteProcResBegin(SC),
114 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
115 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
116 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
117 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000118 }
119 FBI->InstrCount = InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000120
121 // Scale the resource cycles so they are comparable.
122 unsigned PROffset = MBB->getNumber() * PRKinds;
123 for (unsigned K = 0; K != PRKinds; ++K)
124 ProcResourceCycles[PROffset + K] =
125 PRCycles[K] * SchedModel.getResourceFactor(K);
126
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000127 return FBI;
128}
129
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000130ArrayRef<unsigned>
131MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
132 assert(BlockInfo[MBBNum].hasResources() &&
133 "getResources() must be called before getProcResourceCycles()");
134 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
135 return ArrayRef<unsigned>(&ProcResourceCycles[MBBNum * PRKinds], PRKinds);
136}
137
138
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000139//===----------------------------------------------------------------------===//
140// Ensemble utility functions
141//===----------------------------------------------------------------------===//
142
143MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000144 : MTM(*ct) {
145 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000146 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
147 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
148 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000149}
150
151// Virtual destructor serves as an anchor.
152MachineTraceMetrics::Ensemble::~Ensemble() {}
153
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000154const MachineLoop*
155MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000156 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000157}
158
159// Update resource-related information in the TraceBlockInfo for MBB.
160// Only update resources related to the trace above MBB.
161void MachineTraceMetrics::Ensemble::
162computeDepthResources(const MachineBasicBlock *MBB) {
163 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000164 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
165 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000166
167 // Compute resources from trace above. The top block is simple.
168 if (!TBI->Pred) {
169 TBI->InstrDepth = 0;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000170 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000171 std::fill(ProcResourceDepths.begin() + PROffset,
172 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000173 return;
174 }
175
176 // Compute from the block above. A post-order traversal ensures the
177 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000178 unsigned PredNum = TBI->Pred->getNumber();
179 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000180 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000181 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000182 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000183 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000184
185 // Compute per-resource depths.
186 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
187 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
188 for (unsigned K = 0; K != PRKinds; ++K)
189 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000190}
191
192// Update resource-related information in the TraceBlockInfo for MBB.
193// Only update resources related to the trace below MBB.
194void MachineTraceMetrics::Ensemble::
195computeHeightResources(const MachineBasicBlock *MBB) {
196 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000197 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
198 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000199
200 // Compute resources for the current block.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000201 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000202 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000203
204 // The trace tail is done.
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000205 if (!TBI->Succ) {
206 TBI->Tail = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000207 std::copy(PRCycles.begin(), PRCycles.end(),
208 ProcResourceHeights.begin() + PROffset);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000209 return;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000210 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000211
212 // Compute from the block below. A post-order traversal ensures the
213 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000214 unsigned SuccNum = TBI->Succ->getNumber();
215 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000216 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
217 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000218 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000219
220 // Compute per-resource heights.
221 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
222 for (unsigned K = 0; K != PRKinds; ++K)
223 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000224}
225
226// Check if depth resources for MBB are valid and return the TBI.
227// Return NULL if the resources have been invalidated.
228const MachineTraceMetrics::TraceBlockInfo*
229MachineTraceMetrics::Ensemble::
230getDepthResources(const MachineBasicBlock *MBB) const {
231 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
232 return TBI->hasValidDepth() ? TBI : 0;
233}
234
235// Check if height resources for MBB are valid and return the TBI.
236// Return NULL if the resources have been invalidated.
237const MachineTraceMetrics::TraceBlockInfo*
238MachineTraceMetrics::Ensemble::
239getHeightResources(const MachineBasicBlock *MBB) const {
240 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
241 return TBI->hasValidHeight() ? TBI : 0;
242}
243
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000244/// Get an array of processor resource depths for MBB. Indexed by processor
245/// resource kind, this array contains the scaled processor resources consumed
246/// by all blocks preceding MBB in its trace. It does not include instructions
247/// in MBB.
248///
249/// Compare TraceBlockInfo::InstrDepth.
250ArrayRef<unsigned>
251MachineTraceMetrics::Ensemble::
252getProcResourceDepths(unsigned MBBNum) const {
253 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
254 return ArrayRef<unsigned>(&ProcResourceDepths[MBBNum * PRKinds], PRKinds);
255}
256
257/// Get an array of processor resource heights for MBB. Indexed by processor
258/// resource kind, this array contains the scaled processor resources consumed
259/// by this block and all blocks following it in its trace.
260///
261/// Compare TraceBlockInfo::InstrHeight.
262ArrayRef<unsigned>
263MachineTraceMetrics::Ensemble::
264getProcResourceHeights(unsigned MBBNum) const {
265 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
266 return ArrayRef<unsigned>(&ProcResourceHeights[MBBNum * PRKinds], PRKinds);
267}
268
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000269//===----------------------------------------------------------------------===//
270// Trace Selection Strategies
271//===----------------------------------------------------------------------===//
272//
273// A trace selection strategy is implemented as a sub-class of Ensemble. The
274// trace through a block B is computed by two DFS traversals of the CFG
275// starting from B. One upwards, and one downwards. During the upwards DFS,
276// pickTracePred() is called on the post-ordered blocks. During the downwards
277// DFS, pickTraceSucc() is called in a post-order.
278//
279
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000280// We never allow traces that leave loops, but we do allow traces to enter
281// nested loops. We also never allow traces to contain back-edges.
282//
283// This means that a loop header can never appear above the center block of a
284// trace, except as the trace head. Below the center block, loop exiting edges
285// are banned.
286//
287// Return true if an edge from the From loop to the To loop is leaving a loop.
288// Either of To and From can be null.
289static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
290 return From && !From->contains(To);
291}
292
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000293// MinInstrCountEnsemble - Pick the trace that executes the least number of
294// instructions.
295namespace {
296class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +0000297 const char *getName() const { return "MinInstr"; }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000298 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*);
299 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*);
300
301public:
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000302 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
303 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000304};
305}
306
307// Select the preferred predecessor for MBB.
308const MachineBasicBlock*
309MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
310 if (MBB->pred_empty())
311 return 0;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000312 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000313 // Don't leave loops, and never follow back-edges.
314 if (CurLoop && MBB == CurLoop->getHeader())
315 return 0;
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000316 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000317 const MachineBasicBlock *Best = 0;
318 unsigned BestDepth = 0;
319 for (MachineBasicBlock::const_pred_iterator
320 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
321 const MachineBasicBlock *Pred = *I;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000322 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
323 getDepthResources(Pred);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000324 // Ignore cycles that aren't natural loops.
325 if (!PredTBI)
326 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000327 // Pick the predecessor that would give this block the smallest InstrDepth.
328 unsigned Depth = PredTBI->InstrDepth + CurCount;
329 if (!Best || Depth < BestDepth)
330 Best = Pred, BestDepth = Depth;
331 }
332 return Best;
333}
334
335// Select the preferred successor for MBB.
336const MachineBasicBlock*
337MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
338 if (MBB->pred_empty())
339 return 0;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000340 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000341 const MachineBasicBlock *Best = 0;
342 unsigned BestHeight = 0;
343 for (MachineBasicBlock::const_succ_iterator
344 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
345 const MachineBasicBlock *Succ = *I;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000346 // Don't consider back-edges.
347 if (CurLoop && Succ == CurLoop->getHeader())
348 continue;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000349 // Don't consider successors exiting CurLoop.
350 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000351 continue;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000352 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
353 getHeightResources(Succ);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000354 // Ignore cycles that aren't natural loops.
355 if (!SuccTBI)
356 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000357 // Pick the successor that would give this block the smallest InstrHeight.
358 unsigned Height = SuccTBI->InstrHeight;
359 if (!Best || Height < BestHeight)
360 Best = Succ, BestHeight = Height;
361 }
362 return Best;
363}
364
365// Get an Ensemble sub-class for the requested trace strategy.
366MachineTraceMetrics::Ensemble *
367MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
368 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
369 Ensemble *&E = Ensembles[strategy];
370 if (E)
371 return E;
372
373 // Allocate new Ensemble on demand.
374 switch (strategy) {
375 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
376 default: llvm_unreachable("Invalid trace strategy enum");
377 }
378}
379
380void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
381 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
382 BlockInfo[MBB->getNumber()].invalidate();
383 for (unsigned i = 0; i != TS_NumStrategies; ++i)
384 if (Ensembles[i])
385 Ensembles[i]->invalidate(MBB);
386}
387
Jakob Stoklund Olesenef6c76c2012-07-30 20:57:50 +0000388void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +0000389 if (!MF)
390 return;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000391#ifndef NDEBUG
392 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
393 for (unsigned i = 0; i != TS_NumStrategies; ++i)
394 if (Ensembles[i])
395 Ensembles[i]->verify();
396#endif
397}
398
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000399//===----------------------------------------------------------------------===//
400// Trace building
401//===----------------------------------------------------------------------===//
402//
403// Traces are built by two CFG traversals. To avoid recomputing too much, use a
404// set abstraction that confines the search to the current loop, and doesn't
405// revisit blocks.
406
407namespace {
408struct LoopBounds {
409 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000410 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000411 const MachineLoopInfo *Loops;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000412 bool Downward;
413 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000414 const MachineLoopInfo *loops)
415 : Blocks(blocks), Loops(loops), Downward(false) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000416};
417}
418
419// Specialize po_iterator_storage in order to prune the post-order traversal so
420// it is limited to the current loop and doesn't traverse the loop back edges.
421namespace llvm {
422template<>
423class po_iterator_storage<LoopBounds, true> {
424 LoopBounds &LB;
425public:
426 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
427 void finishPostorder(const MachineBasicBlock*) {}
428
429 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
430 // Skip already visited To blocks.
431 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
432 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
433 return false;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000434 // From is null once when To is the trace center block.
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000435 if (From) {
436 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
437 // Don't follow backedges, don't leave FromLoop when going upwards.
438 if ((LB.Downward ? To : From) == FromLoop->getHeader())
439 return false;
440 // Don't leave FromLoop.
441 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
442 return false;
443 }
444 }
445 // To is a new block. Mark the block as visited in case the CFG has cycles
446 // that MachineLoopInfo didn't recognize as a natural loop.
447 return LB.Visited.insert(To);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000448 }
449};
450}
451
452/// Compute the trace through MBB.
453void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
454 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
455 << MBB->getNumber() << '\n');
456 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000457 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000458
459 // Run an upwards post-order search for the trace start.
460 Bounds.Downward = false;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000461 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000462 typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
463 for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
464 I != E; ++I) {
465 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
466 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
467 // All the predecessors have been visited, pick the preferred one.
468 TBI.Pred = pickTracePred(*I);
469 DEBUG({
470 if (TBI.Pred)
471 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
472 else
473 dbgs() << "null\n";
474 });
475 // The trace leading to I is now known, compute the depth resources.
476 computeDepthResources(*I);
477 }
478
479 // Run a downwards post-order search for the trace end.
480 Bounds.Downward = true;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000481 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000482 typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
483 for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
484 I != E; ++I) {
485 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
486 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
487 // All the successors have been visited, pick the preferred one.
Jakob Stoklund Olesen0fc44862012-07-26 19:42:56 +0000488 TBI.Succ = pickTraceSucc(*I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000489 DEBUG({
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000490 if (TBI.Succ)
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000491 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
492 else
493 dbgs() << "null\n";
494 });
495 // The trace leaving I is now known, compute the height resources.
496 computeHeightResources(*I);
497 }
498}
499
500/// Invalidate traces through BadMBB.
501void
502MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
503 SmallVector<const MachineBasicBlock*, 16> WorkList;
504 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
505
506 // Invalidate height resources of blocks above MBB.
507 if (BadTBI.hasValidHeight()) {
508 BadTBI.invalidateHeight();
509 WorkList.push_back(BadMBB);
510 do {
511 const MachineBasicBlock *MBB = WorkList.pop_back_val();
512 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
513 << " height.\n");
514 // Find any MBB predecessors that have MBB as their preferred successor.
515 // They are the only ones that need to be invalidated.
516 for (MachineBasicBlock::const_pred_iterator
517 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
518 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000519 if (!TBI.hasValidHeight())
520 continue;
521 if (TBI.Succ == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000522 TBI.invalidateHeight();
523 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000524 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000525 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000526 // Verify that TBI.Succ is actually a *I successor.
527 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000528 }
529 } while (!WorkList.empty());
530 }
531
532 // Invalidate depth resources of blocks below MBB.
533 if (BadTBI.hasValidDepth()) {
534 BadTBI.invalidateDepth();
535 WorkList.push_back(BadMBB);
536 do {
537 const MachineBasicBlock *MBB = WorkList.pop_back_val();
538 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
539 << " depth.\n");
540 // Find any MBB successors that have MBB as their preferred predecessor.
541 // They are the only ones that need to be invalidated.
542 for (MachineBasicBlock::const_succ_iterator
543 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
544 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000545 if (!TBI.hasValidDepth())
546 continue;
547 if (TBI.Pred == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000548 TBI.invalidateDepth();
549 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000550 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000551 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000552 // Verify that TBI.Pred is actually a *I predecessor.
553 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000554 }
555 } while (!WorkList.empty());
556 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000557
558 // Clear any per-instruction data. We only have to do this for BadMBB itself
559 // because the instructions in that block may change. Other blocks may be
560 // invalidated, but their instructions will stay the same, so there is no
561 // need to erase the Cycle entries. They will be overwritten when we
562 // recompute.
563 for (MachineBasicBlock::const_iterator I = BadMBB->begin(), E = BadMBB->end();
564 I != E; ++I)
565 Cycles.erase(I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000566}
567
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000568void MachineTraceMetrics::Ensemble::verify() const {
569#ifndef NDEBUG
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000570 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000571 "Outdated BlockInfo size");
572 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
573 const TraceBlockInfo &TBI = BlockInfo[Num];
574 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000575 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000576 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
577 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
578 "Trace is broken, depth should have been invalidated.");
579 const MachineLoop *Loop = getLoopFor(MBB);
580 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
581 }
582 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000583 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000584 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
585 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
586 "Trace is broken, height should have been invalidated.");
587 const MachineLoop *Loop = getLoopFor(MBB);
588 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
589 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
590 "Trace contains backedge");
591 }
592 }
593#endif
594}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000595
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000596//===----------------------------------------------------------------------===//
597// Data Dependencies
598//===----------------------------------------------------------------------===//
599//
600// Compute the depth and height of each instruction based on data dependencies
601// and instruction latencies. These cycle numbers assume that the CPU can issue
602// an infinite number of instructions per cycle as long as their dependencies
603// are ready.
604
605// A data dependency is represented as a defining MI and operand numbers on the
606// defining and using MI.
607namespace {
608struct DataDep {
609 const MachineInstr *DefMI;
610 unsigned DefOp;
611 unsigned UseOp;
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000612
613 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
614 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
615
616 /// Create a DataDep from an SSA form virtual register.
617 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
618 : UseOp(UseOp) {
619 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
620 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
621 assert(!DefI.atEnd() && "Register has no defs");
622 DefMI = &*DefI;
623 DefOp = DefI.getOperandNo();
624 assert((++DefI).atEnd() && "Register has multiple defs");
625 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000626};
627}
628
629// Get the input data dependencies that must be ready before UseMI can issue.
630// Return true if UseMI has any physreg operands.
631static bool getDataDeps(const MachineInstr *UseMI,
632 SmallVectorImpl<DataDep> &Deps,
633 const MachineRegisterInfo *MRI) {
634 bool HasPhysRegs = false;
635 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
636 if (!MO->isReg())
637 continue;
638 unsigned Reg = MO->getReg();
639 if (!Reg)
640 continue;
641 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
642 HasPhysRegs = true;
643 continue;
644 }
645 // Collect virtual register reads.
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000646 if (MO->readsReg())
647 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000648 }
649 return HasPhysRegs;
650}
651
652// Get the input data dependencies of a PHI instruction, using Pred as the
653// preferred predecessor.
654// This will add at most one dependency to Deps.
655static void getPHIDeps(const MachineInstr *UseMI,
656 SmallVectorImpl<DataDep> &Deps,
657 const MachineBasicBlock *Pred,
658 const MachineRegisterInfo *MRI) {
659 // No predecessor at the beginning of a trace. Ignore dependencies.
660 if (!Pred)
661 return;
662 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
663 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
664 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
665 unsigned Reg = UseMI->getOperand(i).getReg();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000666 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000667 return;
668 }
669 }
670}
671
672// Keep track of physreg data dependencies by recording each live register unit.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000673// Associate each regunit with an instruction operand. Depending on the
674// direction instructions are scanned, it could be the operand that defined the
675// regunit, or the highest operand to read the regunit.
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000676namespace {
677struct LiveRegUnit {
678 unsigned RegUnit;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000679 unsigned Cycle;
680 const MachineInstr *MI;
681 unsigned Op;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000682
683 unsigned getSparseSetIndex() const { return RegUnit; }
684
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000685 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(0), Op(0) {}
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000686};
687}
688
689// Identify physreg dependencies for UseMI, and update the live regunit
690// tracking set when scanning instructions downwards.
691static void updatePhysDepsDownwards(const MachineInstr *UseMI,
692 SmallVectorImpl<DataDep> &Deps,
693 SparseSet<LiveRegUnit> &RegUnits,
694 const TargetRegisterInfo *TRI) {
695 SmallVector<unsigned, 8> Kills;
696 SmallVector<unsigned, 8> LiveDefOps;
697
698 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
699 if (!MO->isReg())
700 continue;
701 unsigned Reg = MO->getReg();
702 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
703 continue;
704 // Track live defs and kills for updating RegUnits.
705 if (MO->isDef()) {
706 if (MO->isDead())
707 Kills.push_back(Reg);
708 else
709 LiveDefOps.push_back(MO.getOperandNo());
710 } else if (MO->isKill())
711 Kills.push_back(Reg);
712 // Identify dependencies.
713 if (!MO->readsReg())
714 continue;
715 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
716 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
717 if (I == RegUnits.end())
718 continue;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000719 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000720 break;
721 }
722 }
723
724 // Update RegUnits to reflect live registers after UseMI.
725 // First kills.
726 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
727 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
728 RegUnits.erase(*Units);
729
730 // Second, live defs.
731 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
732 unsigned DefOp = LiveDefOps[i];
733 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
734 Units.isValid(); ++Units) {
735 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000736 LRU.MI = UseMI;
737 LRU.Op = DefOp;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000738 }
739 }
740}
741
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000742/// The length of the critical path through a trace is the maximum of two path
743/// lengths:
744///
745/// 1. The maximum height+depth over all instructions in the trace center block.
746///
747/// 2. The longest cross-block dependency chain. For small blocks, it is
748/// possible that the critical path through the trace doesn't include any
749/// instructions in the block.
750///
751/// This function computes the second number from the live-in list of the
752/// center block.
753unsigned MachineTraceMetrics::Ensemble::
754computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
755 assert(TBI.HasValidInstrDepths && "Missing depth info");
756 assert(TBI.HasValidInstrHeights && "Missing height info");
757 unsigned MaxLen = 0;
758 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
759 const LiveInReg &LIR = TBI.LiveIns[i];
760 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
761 continue;
762 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
763 // Ignore dependencies outside the current trace.
764 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000765 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000766 continue;
767 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
768 MaxLen = std::max(MaxLen, Len);
769 }
770 return MaxLen;
771}
772
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000773/// Compute instruction depths for all instructions above or in MBB in its
774/// trace. This assumes that the trace through MBB has already been computed.
775void MachineTraceMetrics::Ensemble::
776computeInstrDepths(const MachineBasicBlock *MBB) {
777 // The top of the trace may already be computed, and HasValidInstrDepths
778 // implies Head->HasValidInstrDepths, so we only need to start from the first
779 // block in the trace that needs to be recomputed.
780 SmallVector<const MachineBasicBlock*, 8> Stack;
781 do {
782 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
783 assert(TBI.hasValidDepth() && "Incomplete trace");
784 if (TBI.HasValidInstrDepths)
785 break;
786 Stack.push_back(MBB);
787 MBB = TBI.Pred;
788 } while (MBB);
789
790 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
791 // in the trace. We should track any live-out physregs that were defined in
792 // the trace. This is quite rare in SSA form, typically created by CSE
793 // hoisting a compare.
794 SparseSet<LiveRegUnit> RegUnits;
795 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
796
797 // Go through trace blocks in top-down order, stopping after the center block.
798 SmallVector<DataDep, 8> Deps;
799 while (!Stack.empty()) {
800 MBB = Stack.pop_back_val();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000801 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000802 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
803 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000804 TBI.CriticalPath = 0;
805
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000806 // Print out resource depths here as well.
807 DEBUG({
808 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
809 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
810 for (unsigned K = 0; K != PRDepths.size(); ++K)
811 if (PRDepths[K]) {
812 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
813 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
814 << MTM.SchedModel.getProcResource(K)->Name << " ("
815 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
816 }
817 });
818
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000819 // Also compute the critical path length through MBB when possible.
820 if (TBI.HasValidInstrHeights)
821 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
822
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000823 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
824 I != E; ++I) {
825 const MachineInstr *UseMI = I;
826
827 // Collect all data dependencies.
828 Deps.clear();
829 if (UseMI->isPHI())
830 getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
831 else if (getDataDeps(UseMI, Deps, MTM.MRI))
832 updatePhysDepsDownwards(UseMI, Deps, RegUnits, MTM.TRI);
833
834 // Filter and process dependencies, computing the earliest issue cycle.
835 unsigned Cycle = 0;
836 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
837 const DataDep &Dep = Deps[i];
838 const TraceBlockInfo&DepTBI =
839 BlockInfo[Dep.DefMI->getParent()->getNumber()];
840 // Ignore dependencies from outside the current trace.
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000841 if (!DepTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000842 continue;
843 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
844 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
845 // Add latency if DefMI is a real instruction. Transients get latency 0.
846 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000847 DepCycle += MTM.SchedModel
848 .computeOperandLatency(Dep.DefMI, Dep.DefOp, UseMI, Dep.UseOp,
849 /* FindMin = */ false);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000850 Cycle = std::max(Cycle, DepCycle);
851 }
852 // Remember the instruction depth.
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000853 InstrCycles &MICycles = Cycles[UseMI];
854 MICycles.Depth = Cycle;
855
856 if (!TBI.HasValidInstrHeights) {
857 DEBUG(dbgs() << Cycle << '\t' << *UseMI);
858 continue;
859 }
860 // Update critical path length.
861 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
862 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *UseMI);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000863 }
864 }
865}
866
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000867// 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.
870static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
871 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000872 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000873 const TargetInstrInfo *TII,
874 const TargetRegisterInfo *TRI) {
875 SmallVector<unsigned, 8> ReadOps;
876 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
877 if (!MO->isReg())
878 continue;
879 unsigned Reg = MO->getReg();
880 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
881 continue;
882 if (MO->readsReg())
883 ReadOps.push_back(MO.getOperandNo());
884 if (!MO->isDef())
885 continue;
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())
891 continue;
892 unsigned DepHeight = I->Cycle;
893 if (!MI->isTransient()) {
894 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000895 // live-in list. SchedModel can handle a NULL UseMI.
896 DepHeight += SchedModel
897 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op,
898 /* FindMin = */ false);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000899 }
900 Height = std::max(Height, DepHeight);
901 // This regunit is dead above MI.
902 RegUnits.erase(I);
903 }
904 }
905
906 // Now we know the height of MI. Update any regunits read.
907 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
908 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
909 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
910 LiveRegUnit &LRU = RegUnits[*Units];
911 // Set the height to the highest reader of the unit.
912 if (LRU.Cycle <= Height && LRU.MI != MI) {
913 LRU.Cycle = Height;
914 LRU.MI = MI;
915 LRU.Op = ReadOps[i];
916 }
917 }
918 }
919
920 return Height;
921}
922
923
924typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
925
926// Push the height of DefMI upwards if required to match UseMI.
927// Return true if this is the first time DefMI was seen.
928static bool pushDepHeight(const DataDep &Dep,
929 const MachineInstr *UseMI, unsigned UseHeight,
930 MIHeightMap &Heights,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000931 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000932 const TargetInstrInfo *TII) {
933 // Adjust height by Dep.DefMI latency.
934 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000935 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
936 UseMI, Dep.UseOp, false);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000937
938 // Update Heights[DefMI] to be the maximum height seen.
939 MIHeightMap::iterator I;
940 bool New;
941 tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
942 if (New)
943 return true;
944
945 // DefMI has been pushed before. Give it the max height.
946 if (I->second < UseHeight)
947 I->second = UseHeight;
948 return false;
949}
950
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000951/// Assuming that the virtual register defined by DefMI:DefOp was used by
952/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
953/// when reaching the block that contains DefMI.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000954void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000955addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000956 ArrayRef<const MachineBasicBlock*> Trace) {
957 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000958 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000959 assert(TargetRegisterInfo::isVirtualRegister(Reg));
960 const MachineBasicBlock *DefMBB = DefMI->getParent();
961
962 // Reg is live-in to all blocks in Trace that follow DefMBB.
963 for (unsigned i = Trace.size(); i; --i) {
964 const MachineBasicBlock *MBB = Trace[i-1];
965 if (MBB == DefMBB)
966 return;
967 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
968 // Just add the register. The height will be updated later.
969 TBI.LiveIns.push_back(Reg);
970 }
971}
972
973/// Compute instruction heights in the trace through MBB. This updates MBB and
974/// the blocks below it in the trace. It is assumed that the trace has already
975/// been computed.
976void MachineTraceMetrics::Ensemble::
977computeInstrHeights(const MachineBasicBlock *MBB) {
978 // The bottom of the trace may already be computed.
979 // Find the blocks that need updating.
980 SmallVector<const MachineBasicBlock*, 8> Stack;
981 do {
982 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
983 assert(TBI.hasValidHeight() && "Incomplete trace");
984 if (TBI.HasValidInstrHeights)
985 break;
986 Stack.push_back(MBB);
987 TBI.LiveIns.clear();
988 MBB = TBI.Succ;
989 } while (MBB);
990
991 // As we move upwards in the trace, keep track of instructions that are
992 // required by deeper trace instructions. Map MI -> height required so far.
993 MIHeightMap Heights;
994
995 // For physregs, the def isn't known when we see the use.
996 // Instead, keep track of the highest use of each regunit.
997 SparseSet<LiveRegUnit> RegUnits;
998 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
999
1000 // If the bottom of the trace was already precomputed, initialize heights
1001 // from its live-in list.
1002 // MBB is the highest precomputed block in the trace.
1003 if (MBB) {
1004 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1005 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1006 LiveInReg LI = TBI.LiveIns[i];
1007 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1008 // For virtual registers, the def latency is included.
1009 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1010 if (Height < LI.Height)
1011 Height = LI.Height;
1012 } else {
1013 // For register units, the def latency is not included because we don't
1014 // know the def yet.
1015 RegUnits[LI.Reg].Cycle = LI.Height;
1016 }
1017 }
1018 }
1019
1020 // Go through the trace blocks in bottom-up order.
1021 SmallVector<DataDep, 8> Deps;
1022 for (;!Stack.empty(); Stack.pop_back()) {
1023 MBB = Stack.back();
1024 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1025 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1026 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001027 TBI.CriticalPath = 0;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001028
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001029 DEBUG({
1030 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1031 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1032 for (unsigned K = 0; K != PRHeights.size(); ++K)
1033 if (PRHeights[K]) {
1034 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1035 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1036 << MTM.SchedModel.getProcResource(K)->Name << " ("
1037 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1038 }
1039 });
1040
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001041 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001042 const MachineBasicBlock *Succ = TBI.Succ;
1043 // If MBB is the last block in the trace, and it has a back-edge to the
1044 // loop header, get loop-carried dependencies from PHIs in the header. For
1045 // that purpose, pretend that all the loop header PHIs have height 0.
1046 if (!Succ)
1047 if (const MachineLoop *Loop = getLoopFor(MBB))
1048 if (MBB->isSuccessor(Loop->getHeader()))
1049 Succ = Loop->getHeader();
1050
1051 if (Succ) {
1052 for (MachineBasicBlock::const_iterator I = Succ->begin(), E = Succ->end();
Jakob Stoklund Olesen7a8f3112012-08-07 18:32:57 +00001053 I != E && I->isPHI(); ++I) {
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001054 const MachineInstr *PHI = I;
1055 Deps.clear();
1056 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001057 if (!Deps.empty()) {
1058 // Loop header PHI heights are all 0.
1059 unsigned Height = TBI.Succ ? Cycles.lookup(PHI).Height : 0;
1060 DEBUG(dbgs() << "pred\t" << Height << '\t' << *PHI);
1061 if (pushDepHeight(Deps.front(), PHI, Height,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001062 Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001063 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001064 }
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001065 }
1066 }
1067
1068 // Go through the block backwards.
1069 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1070 BI != BB;) {
1071 const MachineInstr *MI = --BI;
1072
1073 // Find the MI height as determined by virtual register uses in the
1074 // trace below.
1075 unsigned Cycle = 0;
1076 MIHeightMap::iterator HeightI = Heights.find(MI);
1077 if (HeightI != Heights.end()) {
1078 Cycle = HeightI->second;
1079 // We won't be seeing any more MI uses.
1080 Heights.erase(HeightI);
1081 }
1082
1083 // Don't process PHI deps. They depend on the specific predecessor, and
1084 // we'll get them when visiting the predecessor.
1085 Deps.clear();
1086 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1087
1088 // There may also be regunit dependencies to include in the height.
1089 if (HasPhysRegs)
1090 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001091 MTM.SchedModel, MTM.TII, MTM.TRI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001092
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001093 // Update the required height of any virtual registers read by MI.
1094 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001095 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001096 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001097
1098 InstrCycles &MICycles = Cycles[MI];
1099 MICycles.Height = Cycle;
1100 if (!TBI.HasValidInstrDepths) {
1101 DEBUG(dbgs() << Cycle << '\t' << *MI);
1102 continue;
1103 }
1104 // Update critical path length.
1105 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1106 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001107 }
1108
1109 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1110 // height because the final height isn't known until now.
1111 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
1112 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1113 LiveInReg &LIR = TBI.LiveIns[i];
1114 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1115 LIR.Height = Heights.lookup(DefMI);
1116 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1117 }
1118
1119 // Transfer the live regunits to the live-in list.
1120 for (SparseSet<LiveRegUnit>::const_iterator
1121 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1122 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1123 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1124 << '@' << RI->Cycle);
1125 }
1126 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001127
1128 if (!TBI.HasValidInstrDepths)
1129 continue;
1130 // Add live-ins to the critical path length.
1131 TBI.CriticalPath = std::max(TBI.CriticalPath,
1132 computeCrossBlockCriticalPath(TBI));
1133 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001134 }
1135}
1136
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001137MachineTraceMetrics::Trace
1138MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1139 // FIXME: Check cache tags, recompute as needed.
1140 computeTrace(MBB);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001141 computeInstrDepths(MBB);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001142 computeInstrHeights(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001143 return Trace(*this, BlockInfo[MBB->getNumber()]);
1144}
1145
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001146unsigned
1147MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1148 assert(MI && "Not an instruction.");
1149 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1150 "MI must be in the trace center block");
1151 InstrCycles Cyc = getInstrCycles(MI);
1152 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1153}
1154
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001155unsigned
1156MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1157 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1158 SmallVector<DataDep, 1> Deps;
1159 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1160 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1161 DataDep &Dep = Deps.front();
1162 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1163 // Add latency if DefMI is a real instruction. Transients get latency 0.
1164 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001165 DepCycle += TE.MTM.SchedModel
1166 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp, false);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001167 return DepCycle;
1168}
1169
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001170unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001171 // Find the limiting processor resource.
1172 // Numbers have been pre-scaled to be comparable.
1173 unsigned PRMax = 0;
1174 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1175 if (Bottom) {
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]);
1179 } else {
1180 for (unsigned K = 0; K != PRDepths.size(); ++K)
1181 PRMax = std::max(PRMax, PRDepths[K]);
1182 }
1183 // Convert to cycle count.
1184 PRMax = TE.MTM.getCycles(PRMax);
1185
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001186 unsigned Instrs = TBI.InstrDepth;
1187 if (Bottom)
1188 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001189 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1190 Instrs /= IW;
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001191 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001192 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001193}
1194
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001195unsigned MachineTraceMetrics::Trace::
1196getResourceLength(ArrayRef<const MachineBasicBlock*> Extrablocks) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001197 // Add up resources above and below the center block.
1198 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1199 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1200 unsigned PRMax = 0;
1201 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1202 unsigned PRCycles = PRDepths[K] + PRHeights[K];
1203 for (unsigned I = 0; I != Extrablocks.size(); ++I)
1204 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
1205 PRMax = std::max(PRMax, PRCycles);
1206 }
1207 // Convert to cycle count.
1208 PRMax = TE.MTM.getCycles(PRMax);
1209
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001210 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1211 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1212 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001213 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1214 Instrs /= IW;
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001215 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001216 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001217}
1218
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001219void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1220 OS << getName() << " ensemble:\n";
1221 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1222 OS << " BB#" << i << '\t';
1223 BlockInfo[i].print(OS);
1224 OS << '\n';
1225 }
1226}
1227
1228void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1229 if (hasValidDepth()) {
1230 OS << "depth=" << InstrDepth;
1231 if (Pred)
1232 OS << " pred=BB#" << Pred->getNumber();
1233 else
1234 OS << " pred=null";
1235 OS << " head=BB#" << Head;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001236 if (HasValidInstrDepths)
1237 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001238 } else
1239 OS << "depth invalid";
1240 OS << ", ";
1241 if (hasValidHeight()) {
1242 OS << "height=" << InstrHeight;
1243 if (Succ)
1244 OS << " succ=BB#" << Succ->getNumber();
1245 else
1246 OS << " succ=null";
1247 OS << " tail=BB#" << Tail;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001248 if (HasValidInstrHeights)
1249 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001250 } else
1251 OS << "height invalid";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001252 if (HasValidInstrDepths && HasValidInstrHeights)
1253 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001254}
1255
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001256void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001257 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1258
1259 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1260 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001261 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1262 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001263 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1264 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001265
1266 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001267 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001268 while (Block->hasValidDepth() && Block->Pred) {
1269 unsigned Num = Block->Pred->getNumber();
1270 OS << " <- BB#" << Num;
1271 Block = &TE.BlockInfo[Num];
1272 }
1273
1274 Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001275 OS << "\n ";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001276 while (Block->hasValidHeight() && Block->Succ) {
1277 unsigned Num = Block->Succ->getNumber();
1278 OS << " -> BB#" << Num;
1279 Block = &TE.BlockInfo[Num];
1280 }
1281 OS << '\n';
1282}