blob: 1bbf0ade6a5805fb09b2a303379968471966599f [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 Olesen5ed625c2013-01-17 01:06:04 +000010#include "llvm/CodeGen/MachineTraceMetrics.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000011#include "llvm/ADT/PostOrderIterator.h"
12#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000013#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"
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000018#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000019#include "llvm/Support/Debug.h"
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000020#include "llvm/Support/Format.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000021#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000022#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/Target/TargetRegisterInfo.h"
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000024#include "llvm/Target/TargetSubtargetInfo.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000025
26using namespace llvm;
27
Stephen Hinesdce4a402014-05-29 02:49:00 -070028#define DEBUG_TYPE "machine-trace-metrics"
29
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000030char MachineTraceMetrics::ID = 0;
31char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
32
33INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
34 "machine-trace-metrics", "Machine Trace Metrics", false, true)
35INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
36INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
37INITIALIZE_PASS_END(MachineTraceMetrics,
38 "machine-trace-metrics", "Machine Trace Metrics", false, true)
39
40MachineTraceMetrics::MachineTraceMetrics()
Stephen Hinesdce4a402014-05-29 02:49:00 -070041 : MachineFunctionPass(ID), MF(nullptr), TII(nullptr), TRI(nullptr),
42 MRI(nullptr), Loops(nullptr) {
43 std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000044}
45
46void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.setPreservesAll();
48 AU.addRequired<MachineBranchProbabilityInfo>();
49 AU.addRequired<MachineLoopInfo>();
50 MachineFunctionPass::getAnalysisUsage(AU);
51}
52
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000053bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
54 MF = &Func;
55 TII = MF->getTarget().getInstrInfo();
56 TRI = MF->getTarget().getRegisterInfo();
57 MRI = &MF->getRegInfo();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000058 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000059 const TargetSubtargetInfo &ST =
60 MF->getTarget().getSubtarget<TargetSubtargetInfo>();
61 SchedModel.init(*ST.getSchedModel(), &ST, TII);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000062 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000063 ProcResourceCycles.resize(MF->getNumBlockIDs() *
64 SchedModel.getNumProcResourceKinds());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000065 return false;
66}
67
68void MachineTraceMetrics::releaseMemory() {
Stephen Hinesdce4a402014-05-29 02:49:00 -070069 MF = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000070 BlockInfo.clear();
71 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
72 delete Ensembles[i];
Stephen Hinesdce4a402014-05-29 02:49:00 -070073 Ensembles[i] = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000074 }
75}
76
77//===----------------------------------------------------------------------===//
78// Fixed block information
79//===----------------------------------------------------------------------===//
80//
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.
83
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000084/// Compute the resource usage in basic block MBB.
85const MachineTraceMetrics::FixedBlockInfo*
86MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
87 assert(MBB && "No basic block");
88 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
89 if (FBI->hasResources())
90 return FBI;
91
92 // Compute resource usage in the block.
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000093 FBI->HasCalls = false;
94 unsigned InstrCount = 0;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000095
96 // Add up per-processor resource cycles as well.
97 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
98 SmallVector<unsigned, 32> PRCycles(PRKinds);
99
Stephen Hinesdce4a402014-05-29 02:49:00 -0700100 for (const auto &MI : *MBB) {
101 if (MI.isTransient())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000102 continue;
103 ++InstrCount;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700104 if (MI.isCall())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000105 FBI->HasCalls = true;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000106
107 // Count processor resources used.
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000108 if (!SchedModel.hasInstrSchedModel())
109 continue;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700110 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000111 if (!SC->isValid())
112 continue;
113
114 for (TargetSchedModel::ProcResIter
115 PI = SchedModel.getWriteProcResBegin(SC),
116 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
117 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
118 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
119 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000120 }
121 FBI->InstrCount = InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000122
123 // Scale the resource cycles so they are comparable.
124 unsigned PROffset = MBB->getNumber() * PRKinds;
125 for (unsigned K = 0; K != PRKinds; ++K)
126 ProcResourceCycles[PROffset + K] =
127 PRCycles[K] * SchedModel.getResourceFactor(K);
128
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000129 return FBI;
130}
131
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000132ArrayRef<unsigned>
133MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
134 assert(BlockInfo[MBBNum].hasResources() &&
135 "getResources() must be called before getProcResourceCycles()");
136 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000137 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
138 return ArrayRef<unsigned>(ProcResourceCycles.data() + MBBNum * PRKinds,
139 PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000140}
141
142
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000143//===----------------------------------------------------------------------===//
144// Ensemble utility functions
145//===----------------------------------------------------------------------===//
146
147MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000148 : MTM(*ct) {
149 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000150 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
151 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
152 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000153}
154
155// Virtual destructor serves as an anchor.
156MachineTraceMetrics::Ensemble::~Ensemble() {}
157
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000158const MachineLoop*
159MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000160 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000161}
162
163// Update resource-related information in the TraceBlockInfo for MBB.
164// Only update resources related to the trace above MBB.
165void MachineTraceMetrics::Ensemble::
166computeDepthResources(const MachineBasicBlock *MBB) {
167 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000168 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
169 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000170
171 // Compute resources from trace above. The top block is simple.
172 if (!TBI->Pred) {
173 TBI->InstrDepth = 0;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000174 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000175 std::fill(ProcResourceDepths.begin() + PROffset,
176 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000177 return;
178 }
179
180 // Compute from the block above. A post-order traversal ensures the
181 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000182 unsigned PredNum = TBI->Pred->getNumber();
183 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000184 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000185 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000186 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000187 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000188
189 // Compute per-resource depths.
190 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
191 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
192 for (unsigned K = 0; K != PRKinds; ++K)
193 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000194}
195
196// Update resource-related information in the TraceBlockInfo for MBB.
197// Only update resources related to the trace below MBB.
198void MachineTraceMetrics::Ensemble::
199computeHeightResources(const MachineBasicBlock *MBB) {
200 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000201 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
202 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000203
204 // Compute resources for the current block.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000205 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000206 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000207
208 // The trace tail is done.
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000209 if (!TBI->Succ) {
210 TBI->Tail = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000211 std::copy(PRCycles.begin(), PRCycles.end(),
212 ProcResourceHeights.begin() + PROffset);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000213 return;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000214 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000215
216 // Compute from the block below. A post-order traversal ensures the
217 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000218 unsigned SuccNum = TBI->Succ->getNumber();
219 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000220 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
221 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000222 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000223
224 // Compute per-resource heights.
225 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
226 for (unsigned K = 0; K != PRKinds; ++K)
227 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000228}
229
230// Check if depth resources for MBB are valid and return the TBI.
231// Return NULL if the resources have been invalidated.
232const MachineTraceMetrics::TraceBlockInfo*
233MachineTraceMetrics::Ensemble::
234getDepthResources(const MachineBasicBlock *MBB) const {
235 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700236 return TBI->hasValidDepth() ? TBI : nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000237}
238
239// Check if height resources for MBB are valid and return the TBI.
240// Return NULL if the resources have been invalidated.
241const MachineTraceMetrics::TraceBlockInfo*
242MachineTraceMetrics::Ensemble::
243getHeightResources(const MachineBasicBlock *MBB) const {
244 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700245 return TBI->hasValidHeight() ? TBI : nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000246}
247
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000248/// Get an array of processor resource depths for MBB. Indexed by processor
249/// resource kind, this array contains the scaled processor resources consumed
250/// by all blocks preceding MBB in its trace. It does not include instructions
251/// in MBB.
252///
253/// Compare TraceBlockInfo::InstrDepth.
254ArrayRef<unsigned>
255MachineTraceMetrics::Ensemble::
256getProcResourceDepths(unsigned MBBNum) const {
257 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000258 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
259 return ArrayRef<unsigned>(ProcResourceDepths.data() + MBBNum * PRKinds,
260 PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000261}
262
263/// Get an array of processor resource heights for MBB. Indexed by processor
264/// resource kind, this array contains the scaled processor resources consumed
265/// by this block and all blocks following it in its trace.
266///
267/// Compare TraceBlockInfo::InstrHeight.
268ArrayRef<unsigned>
269MachineTraceMetrics::Ensemble::
270getProcResourceHeights(unsigned MBBNum) const {
271 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000272 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
273 return ArrayRef<unsigned>(ProcResourceHeights.data() + MBBNum * PRKinds,
274 PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000275}
276
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000277//===----------------------------------------------------------------------===//
278// Trace Selection Strategies
279//===----------------------------------------------------------------------===//
280//
281// A trace selection strategy is implemented as a sub-class of Ensemble. The
282// trace through a block B is computed by two DFS traversals of the CFG
283// starting from B. One upwards, and one downwards. During the upwards DFS,
284// pickTracePred() is called on the post-ordered blocks. During the downwards
285// DFS, pickTraceSucc() is called in a post-order.
286//
287
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000288// We never allow traces that leave loops, but we do allow traces to enter
289// nested loops. We also never allow traces to contain back-edges.
290//
291// This means that a loop header can never appear above the center block of a
292// trace, except as the trace head. Below the center block, loop exiting edges
293// are banned.
294//
295// Return true if an edge from the From loop to the To loop is leaving a loop.
296// Either of To and From can be null.
297static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
298 return From && !From->contains(To);
299}
300
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000301// MinInstrCountEnsemble - Pick the trace that executes the least number of
302// instructions.
303namespace {
304class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Stephen Hines36b56882014-04-23 16:57:46 -0700305 const char *getName() const override { return "MinInstr"; }
306 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
307 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000308
309public:
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000310 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
311 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000312};
313}
314
315// Select the preferred predecessor for MBB.
316const MachineBasicBlock*
317MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
318 if (MBB->pred_empty())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700319 return nullptr;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000320 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000321 // Don't leave loops, and never follow back-edges.
322 if (CurLoop && MBB == CurLoop->getHeader())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700323 return nullptr;
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000324 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700325 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000326 unsigned BestDepth = 0;
327 for (MachineBasicBlock::const_pred_iterator
328 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
329 const MachineBasicBlock *Pred = *I;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000330 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
331 getDepthResources(Pred);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000332 // Ignore cycles that aren't natural loops.
333 if (!PredTBI)
334 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000335 // Pick the predecessor that would give this block the smallest InstrDepth.
336 unsigned Depth = PredTBI->InstrDepth + CurCount;
337 if (!Best || Depth < BestDepth)
338 Best = Pred, BestDepth = Depth;
339 }
340 return Best;
341}
342
343// Select the preferred successor for MBB.
344const MachineBasicBlock*
345MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
346 if (MBB->pred_empty())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700347 return nullptr;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000348 const MachineLoop *CurLoop = getLoopFor(MBB);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700349 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000350 unsigned BestHeight = 0;
351 for (MachineBasicBlock::const_succ_iterator
352 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
353 const MachineBasicBlock *Succ = *I;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000354 // Don't consider back-edges.
355 if (CurLoop && Succ == CurLoop->getHeader())
356 continue;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000357 // Don't consider successors exiting CurLoop.
358 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000359 continue;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000360 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
361 getHeightResources(Succ);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000362 // Ignore cycles that aren't natural loops.
363 if (!SuccTBI)
364 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000365 // Pick the successor that would give this block the smallest InstrHeight.
366 unsigned Height = SuccTBI->InstrHeight;
367 if (!Best || Height < BestHeight)
368 Best = Succ, BestHeight = Height;
369 }
370 return Best;
371}
372
373// Get an Ensemble sub-class for the requested trace strategy.
374MachineTraceMetrics::Ensemble *
375MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
376 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
377 Ensemble *&E = Ensembles[strategy];
378 if (E)
379 return E;
380
381 // Allocate new Ensemble on demand.
382 switch (strategy) {
383 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
384 default: llvm_unreachable("Invalid trace strategy enum");
385 }
386}
387
388void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
389 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
390 BlockInfo[MBB->getNumber()].invalidate();
391 for (unsigned i = 0; i != TS_NumStrategies; ++i)
392 if (Ensembles[i])
393 Ensembles[i]->invalidate(MBB);
394}
395
Jakob Stoklund Olesenef6c76c2012-07-30 20:57:50 +0000396void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +0000397 if (!MF)
398 return;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000399#ifndef NDEBUG
400 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
401 for (unsigned i = 0; i != TS_NumStrategies; ++i)
402 if (Ensembles[i])
403 Ensembles[i]->verify();
404#endif
405}
406
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000407//===----------------------------------------------------------------------===//
408// Trace building
409//===----------------------------------------------------------------------===//
410//
411// Traces are built by two CFG traversals. To avoid recomputing too much, use a
412// set abstraction that confines the search to the current loop, and doesn't
413// revisit blocks.
414
415namespace {
416struct LoopBounds {
417 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000418 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000419 const MachineLoopInfo *Loops;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000420 bool Downward;
421 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000422 const MachineLoopInfo *loops)
423 : Blocks(blocks), Loops(loops), Downward(false) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000424};
425}
426
427// Specialize po_iterator_storage in order to prune the post-order traversal so
428// it is limited to the current loop and doesn't traverse the loop back edges.
429namespace llvm {
430template<>
431class po_iterator_storage<LoopBounds, true> {
432 LoopBounds &LB;
433public:
434 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
435 void finishPostorder(const MachineBasicBlock*) {}
436
437 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
438 // Skip already visited To blocks.
439 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
440 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
441 return false;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000442 // From is null once when To is the trace center block.
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000443 if (From) {
444 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
445 // Don't follow backedges, don't leave FromLoop when going upwards.
446 if ((LB.Downward ? To : From) == FromLoop->getHeader())
447 return false;
448 // Don't leave FromLoop.
449 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
450 return false;
451 }
452 }
453 // To is a new block. Mark the block as visited in case the CFG has cycles
454 // that MachineLoopInfo didn't recognize as a natural loop.
455 return LB.Visited.insert(To);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000456 }
457};
458}
459
460/// Compute the trace through MBB.
461void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
462 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
463 << MBB->getNumber() << '\n');
464 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000465 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000466
467 // Run an upwards post-order search for the trace start.
468 Bounds.Downward = false;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000469 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000470 typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
471 for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
472 I != E; ++I) {
473 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
474 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
475 // All the predecessors have been visited, pick the preferred one.
476 TBI.Pred = pickTracePred(*I);
477 DEBUG({
478 if (TBI.Pred)
479 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
480 else
481 dbgs() << "null\n";
482 });
483 // The trace leading to I is now known, compute the depth resources.
484 computeDepthResources(*I);
485 }
486
487 // Run a downwards post-order search for the trace end.
488 Bounds.Downward = true;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000489 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000490 typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
491 for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
492 I != E; ++I) {
493 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
494 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
495 // All the successors have been visited, pick the preferred one.
Jakob Stoklund Olesen0fc44862012-07-26 19:42:56 +0000496 TBI.Succ = pickTraceSucc(*I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000497 DEBUG({
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000498 if (TBI.Succ)
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000499 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
500 else
501 dbgs() << "null\n";
502 });
503 // The trace leaving I is now known, compute the height resources.
504 computeHeightResources(*I);
505 }
506}
507
508/// Invalidate traces through BadMBB.
509void
510MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
511 SmallVector<const MachineBasicBlock*, 16> WorkList;
512 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
513
514 // Invalidate height resources of blocks above MBB.
515 if (BadTBI.hasValidHeight()) {
516 BadTBI.invalidateHeight();
517 WorkList.push_back(BadMBB);
518 do {
519 const MachineBasicBlock *MBB = WorkList.pop_back_val();
520 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
521 << " height.\n");
522 // Find any MBB predecessors that have MBB as their preferred successor.
523 // They are the only ones that need to be invalidated.
524 for (MachineBasicBlock::const_pred_iterator
525 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
526 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000527 if (!TBI.hasValidHeight())
528 continue;
529 if (TBI.Succ == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000530 TBI.invalidateHeight();
531 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000532 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000533 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000534 // Verify that TBI.Succ is actually a *I successor.
535 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000536 }
537 } while (!WorkList.empty());
538 }
539
540 // Invalidate depth resources of blocks below MBB.
541 if (BadTBI.hasValidDepth()) {
542 BadTBI.invalidateDepth();
543 WorkList.push_back(BadMBB);
544 do {
545 const MachineBasicBlock *MBB = WorkList.pop_back_val();
546 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
547 << " depth.\n");
548 // Find any MBB successors that have MBB as their preferred predecessor.
549 // They are the only ones that need to be invalidated.
550 for (MachineBasicBlock::const_succ_iterator
551 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
552 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000553 if (!TBI.hasValidDepth())
554 continue;
555 if (TBI.Pred == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000556 TBI.invalidateDepth();
557 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000558 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000559 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000560 // Verify that TBI.Pred is actually a *I predecessor.
561 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000562 }
563 } while (!WorkList.empty());
564 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000565
566 // Clear any per-instruction data. We only have to do this for BadMBB itself
567 // because the instructions in that block may change. Other blocks may be
568 // invalidated, but their instructions will stay the same, so there is no
569 // need to erase the Cycle entries. They will be overwritten when we
570 // recompute.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700571 for (const auto &I : *BadMBB)
572 Cycles.erase(&I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000573}
574
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000575void MachineTraceMetrics::Ensemble::verify() const {
576#ifndef NDEBUG
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000577 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000578 "Outdated BlockInfo size");
579 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
580 const TraceBlockInfo &TBI = BlockInfo[Num];
581 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000582 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000583 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
584 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
585 "Trace is broken, depth should have been invalidated.");
586 const MachineLoop *Loop = getLoopFor(MBB);
587 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
588 }
589 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000590 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000591 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
592 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
593 "Trace is broken, height should have been invalidated.");
594 const MachineLoop *Loop = getLoopFor(MBB);
595 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
596 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
597 "Trace contains backedge");
598 }
599 }
600#endif
601}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000602
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000603//===----------------------------------------------------------------------===//
604// Data Dependencies
605//===----------------------------------------------------------------------===//
606//
607// Compute the depth and height of each instruction based on data dependencies
608// and instruction latencies. These cycle numbers assume that the CPU can issue
609// an infinite number of instructions per cycle as long as their dependencies
610// are ready.
611
612// A data dependency is represented as a defining MI and operand numbers on the
613// defining and using MI.
614namespace {
615struct DataDep {
616 const MachineInstr *DefMI;
617 unsigned DefOp;
618 unsigned UseOp;
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000619
620 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
621 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
622
623 /// Create a DataDep from an SSA form virtual register.
624 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
625 : UseOp(UseOp) {
626 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
627 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
628 assert(!DefI.atEnd() && "Register has no defs");
Stephen Hines36b56882014-04-23 16:57:46 -0700629 DefMI = DefI->getParent();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000630 DefOp = DefI.getOperandNo();
631 assert((++DefI).atEnd() && "Register has multiple defs");
632 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000633};
634}
635
636// Get the input data dependencies that must be ready before UseMI can issue.
637// Return true if UseMI has any physreg operands.
638static bool getDataDeps(const MachineInstr *UseMI,
639 SmallVectorImpl<DataDep> &Deps,
640 const MachineRegisterInfo *MRI) {
641 bool HasPhysRegs = false;
642 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
643 if (!MO->isReg())
644 continue;
645 unsigned Reg = MO->getReg();
646 if (!Reg)
647 continue;
648 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
649 HasPhysRegs = true;
650 continue;
651 }
652 // Collect virtual register reads.
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000653 if (MO->readsReg())
654 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000655 }
656 return HasPhysRegs;
657}
658
659// Get the input data dependencies of a PHI instruction, using Pred as the
660// preferred predecessor.
661// This will add at most one dependency to Deps.
662static void getPHIDeps(const MachineInstr *UseMI,
663 SmallVectorImpl<DataDep> &Deps,
664 const MachineBasicBlock *Pred,
665 const MachineRegisterInfo *MRI) {
666 // No predecessor at the beginning of a trace. Ignore dependencies.
667 if (!Pred)
668 return;
669 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
670 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
671 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
672 unsigned Reg = UseMI->getOperand(i).getReg();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000673 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000674 return;
675 }
676 }
677}
678
679// Keep track of physreg data dependencies by recording each live register unit.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000680// Associate each regunit with an instruction operand. Depending on the
681// direction instructions are scanned, it could be the operand that defined the
682// regunit, or the highest operand to read the regunit.
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000683namespace {
684struct LiveRegUnit {
685 unsigned RegUnit;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000686 unsigned Cycle;
687 const MachineInstr *MI;
688 unsigned Op;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000689
690 unsigned getSparseSetIndex() const { return RegUnit; }
691
Stephen Hinesdce4a402014-05-29 02:49:00 -0700692 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {}
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000693};
694}
695
696// Identify physreg dependencies for UseMI, and update the live regunit
697// tracking set when scanning instructions downwards.
698static void updatePhysDepsDownwards(const MachineInstr *UseMI,
699 SmallVectorImpl<DataDep> &Deps,
700 SparseSet<LiveRegUnit> &RegUnits,
701 const TargetRegisterInfo *TRI) {
702 SmallVector<unsigned, 8> Kills;
703 SmallVector<unsigned, 8> LiveDefOps;
704
705 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
706 if (!MO->isReg())
707 continue;
708 unsigned Reg = MO->getReg();
709 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
710 continue;
711 // Track live defs and kills for updating RegUnits.
712 if (MO->isDef()) {
713 if (MO->isDead())
714 Kills.push_back(Reg);
715 else
716 LiveDefOps.push_back(MO.getOperandNo());
717 } else if (MO->isKill())
718 Kills.push_back(Reg);
719 // Identify dependencies.
720 if (!MO->readsReg())
721 continue;
722 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
723 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
724 if (I == RegUnits.end())
725 continue;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000726 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000727 break;
728 }
729 }
730
731 // Update RegUnits to reflect live registers after UseMI.
732 // First kills.
733 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
734 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
735 RegUnits.erase(*Units);
736
737 // Second, live defs.
738 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
739 unsigned DefOp = LiveDefOps[i];
740 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
741 Units.isValid(); ++Units) {
742 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000743 LRU.MI = UseMI;
744 LRU.Op = DefOp;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000745 }
746 }
747}
748
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000749/// The length of the critical path through a trace is the maximum of two path
750/// lengths:
751///
752/// 1. The maximum height+depth over all instructions in the trace center block.
753///
754/// 2. The longest cross-block dependency chain. For small blocks, it is
755/// possible that the critical path through the trace doesn't include any
756/// instructions in the block.
757///
758/// This function computes the second number from the live-in list of the
759/// center block.
760unsigned MachineTraceMetrics::Ensemble::
761computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
762 assert(TBI.HasValidInstrDepths && "Missing depth info");
763 assert(TBI.HasValidInstrHeights && "Missing height info");
764 unsigned MaxLen = 0;
765 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
766 const LiveInReg &LIR = TBI.LiveIns[i];
767 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
768 continue;
769 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
770 // Ignore dependencies outside the current trace.
771 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000772 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000773 continue;
774 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
775 MaxLen = std::max(MaxLen, Len);
776 }
777 return MaxLen;
778}
779
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000780/// Compute instruction depths for all instructions above or in MBB in its
781/// trace. This assumes that the trace through MBB has already been computed.
782void MachineTraceMetrics::Ensemble::
783computeInstrDepths(const MachineBasicBlock *MBB) {
784 // The top of the trace may already be computed, and HasValidInstrDepths
785 // implies Head->HasValidInstrDepths, so we only need to start from the first
786 // block in the trace that needs to be recomputed.
787 SmallVector<const MachineBasicBlock*, 8> Stack;
788 do {
789 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
790 assert(TBI.hasValidDepth() && "Incomplete trace");
791 if (TBI.HasValidInstrDepths)
792 break;
793 Stack.push_back(MBB);
794 MBB = TBI.Pred;
795 } while (MBB);
796
797 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
798 // in the trace. We should track any live-out physregs that were defined in
799 // the trace. This is quite rare in SSA form, typically created by CSE
800 // hoisting a compare.
801 SparseSet<LiveRegUnit> RegUnits;
802 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
803
804 // Go through trace blocks in top-down order, stopping after the center block.
805 SmallVector<DataDep, 8> Deps;
806 while (!Stack.empty()) {
807 MBB = Stack.pop_back_val();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000808 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000809 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
810 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000811 TBI.CriticalPath = 0;
812
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000813 // Print out resource depths here as well.
814 DEBUG({
815 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
816 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
817 for (unsigned K = 0; K != PRDepths.size(); ++K)
818 if (PRDepths[K]) {
819 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
820 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
821 << MTM.SchedModel.getProcResource(K)->Name << " ("
822 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
823 }
824 });
825
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000826 // Also compute the critical path length through MBB when possible.
827 if (TBI.HasValidInstrHeights)
828 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
829
Stephen Hinesdce4a402014-05-29 02:49:00 -0700830 for (const auto &UseMI : *MBB) {
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000831 // Collect all data dependencies.
832 Deps.clear();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700833 if (UseMI.isPHI())
834 getPHIDeps(&UseMI, Deps, TBI.Pred, MTM.MRI);
835 else if (getDataDeps(&UseMI, Deps, MTM.MRI))
836 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000837
838 // Filter and process dependencies, computing the earliest issue cycle.
839 unsigned Cycle = 0;
840 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
841 const DataDep &Dep = Deps[i];
842 const TraceBlockInfo&DepTBI =
843 BlockInfo[Dep.DefMI->getParent()->getNumber()];
844 // Ignore dependencies from outside the current trace.
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000845 if (!DepTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000846 continue;
847 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
848 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
849 // Add latency if DefMI is a real instruction. Transients get latency 0.
850 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000851 DepCycle += MTM.SchedModel
Stephen Hinesdce4a402014-05-29 02:49:00 -0700852 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000853 Cycle = std::max(Cycle, DepCycle);
854 }
855 // Remember the instruction depth.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700856 InstrCycles &MICycles = Cycles[&UseMI];
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000857 MICycles.Depth = Cycle;
858
859 if (!TBI.HasValidInstrHeights) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700860 DEBUG(dbgs() << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000861 continue;
862 }
863 // Update critical path length.
864 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700865 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000866 }
867 }
868}
869
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000870// Identify physreg dependencies for MI when scanning instructions upwards.
871// Return the issue height of MI after considering any live regunits.
872// Height is the issue height computed from virtual register dependencies alone.
873static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
874 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000875 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000876 const TargetInstrInfo *TII,
877 const TargetRegisterInfo *TRI) {
878 SmallVector<unsigned, 8> ReadOps;
879 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
880 if (!MO->isReg())
881 continue;
882 unsigned Reg = MO->getReg();
883 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
884 continue;
885 if (MO->readsReg())
886 ReadOps.push_back(MO.getOperandNo());
887 if (!MO->isDef())
888 continue;
889 // This is a def of Reg. Remove corresponding entries from RegUnits, and
890 // update MI Height to consider the physreg dependencies.
891 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
892 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
893 if (I == RegUnits.end())
894 continue;
895 unsigned DepHeight = I->Cycle;
896 if (!MI->isTransient()) {
897 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000898 // live-in list. SchedModel can handle a NULL UseMI.
899 DepHeight += SchedModel
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000900 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000901 }
902 Height = std::max(Height, DepHeight);
903 // This regunit is dead above MI.
904 RegUnits.erase(I);
905 }
906 }
907
908 // Now we know the height of MI. Update any regunits read.
909 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
910 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
911 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
912 LiveRegUnit &LRU = RegUnits[*Units];
913 // Set the height to the highest reader of the unit.
914 if (LRU.Cycle <= Height && LRU.MI != MI) {
915 LRU.Cycle = Height;
916 LRU.MI = MI;
917 LRU.Op = ReadOps[i];
918 }
919 }
920 }
921
922 return Height;
923}
924
925
926typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
927
928// Push the height of DefMI upwards if required to match UseMI.
929// Return true if this is the first time DefMI was seen.
930static bool pushDepHeight(const DataDep &Dep,
931 const MachineInstr *UseMI, unsigned UseHeight,
932 MIHeightMap &Heights,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000933 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000934 const TargetInstrInfo *TII) {
935 // Adjust height by Dep.DefMI latency.
936 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000937 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000938 UseMI, Dep.UseOp);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000939
940 // Update Heights[DefMI] to be the maximum height seen.
941 MIHeightMap::iterator I;
942 bool New;
Stephen Hines36b56882014-04-23 16:57:46 -0700943 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000944 if (New)
945 return true;
946
947 // DefMI has been pushed before. Give it the max height.
948 if (I->second < UseHeight)
949 I->second = UseHeight;
950 return false;
951}
952
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000953/// Assuming that the virtual register defined by DefMI:DefOp was used by
954/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
955/// when reaching the block that contains DefMI.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000956void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000957addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000958 ArrayRef<const MachineBasicBlock*> Trace) {
959 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000960 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000961 assert(TargetRegisterInfo::isVirtualRegister(Reg));
962 const MachineBasicBlock *DefMBB = DefMI->getParent();
963
964 // Reg is live-in to all blocks in Trace that follow DefMBB.
965 for (unsigned i = Trace.size(); i; --i) {
966 const MachineBasicBlock *MBB = Trace[i-1];
967 if (MBB == DefMBB)
968 return;
969 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
970 // Just add the register. The height will be updated later.
971 TBI.LiveIns.push_back(Reg);
972 }
973}
974
975/// Compute instruction heights in the trace through MBB. This updates MBB and
976/// the blocks below it in the trace. It is assumed that the trace has already
977/// been computed.
978void MachineTraceMetrics::Ensemble::
979computeInstrHeights(const MachineBasicBlock *MBB) {
980 // The bottom of the trace may already be computed.
981 // Find the blocks that need updating.
982 SmallVector<const MachineBasicBlock*, 8> Stack;
983 do {
984 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
985 assert(TBI.hasValidHeight() && "Incomplete trace");
986 if (TBI.HasValidInstrHeights)
987 break;
988 Stack.push_back(MBB);
989 TBI.LiveIns.clear();
990 MBB = TBI.Succ;
991 } while (MBB);
992
993 // As we move upwards in the trace, keep track of instructions that are
994 // required by deeper trace instructions. Map MI -> height required so far.
995 MIHeightMap Heights;
996
997 // For physregs, the def isn't known when we see the use.
998 // Instead, keep track of the highest use of each regunit.
999 SparseSet<LiveRegUnit> RegUnits;
1000 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1001
1002 // If the bottom of the trace was already precomputed, initialize heights
1003 // from its live-in list.
1004 // MBB is the highest precomputed block in the trace.
1005 if (MBB) {
1006 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1007 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1008 LiveInReg LI = TBI.LiveIns[i];
1009 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1010 // For virtual registers, the def latency is included.
1011 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1012 if (Height < LI.Height)
1013 Height = LI.Height;
1014 } else {
1015 // For register units, the def latency is not included because we don't
1016 // know the def yet.
1017 RegUnits[LI.Reg].Cycle = LI.Height;
1018 }
1019 }
1020 }
1021
1022 // Go through the trace blocks in bottom-up order.
1023 SmallVector<DataDep, 8> Deps;
1024 for (;!Stack.empty(); Stack.pop_back()) {
1025 MBB = Stack.back();
1026 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1027 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1028 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001029 TBI.CriticalPath = 0;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001030
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001031 DEBUG({
1032 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1033 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1034 for (unsigned K = 0; K != PRHeights.size(); ++K)
1035 if (PRHeights[K]) {
1036 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1037 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1038 << MTM.SchedModel.getProcResource(K)->Name << " ("
1039 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1040 }
1041 });
1042
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001043 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001044 const MachineBasicBlock *Succ = TBI.Succ;
1045 // If MBB is the last block in the trace, and it has a back-edge to the
1046 // loop header, get loop-carried dependencies from PHIs in the header. For
1047 // that purpose, pretend that all the loop header PHIs have height 0.
1048 if (!Succ)
1049 if (const MachineLoop *Loop = getLoopFor(MBB))
1050 if (MBB->isSuccessor(Loop->getHeader()))
1051 Succ = Loop->getHeader();
1052
1053 if (Succ) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001054 for (const auto &PHI : *Succ) {
1055 if (!PHI.isPHI())
1056 break;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001057 Deps.clear();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001058 getPHIDeps(&PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001059 if (!Deps.empty()) {
1060 // Loop header PHI heights are all 0.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001061 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1062 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
1063 if (pushDepHeight(Deps.front(), &PHI, Height,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001064 Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001065 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001066 }
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001067 }
1068 }
1069
1070 // Go through the block backwards.
1071 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1072 BI != BB;) {
1073 const MachineInstr *MI = --BI;
1074
1075 // Find the MI height as determined by virtual register uses in the
1076 // trace below.
1077 unsigned Cycle = 0;
1078 MIHeightMap::iterator HeightI = Heights.find(MI);
1079 if (HeightI != Heights.end()) {
1080 Cycle = HeightI->second;
1081 // We won't be seeing any more MI uses.
1082 Heights.erase(HeightI);
1083 }
1084
1085 // Don't process PHI deps. They depend on the specific predecessor, and
1086 // we'll get them when visiting the predecessor.
1087 Deps.clear();
1088 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1089
1090 // There may also be regunit dependencies to include in the height.
1091 if (HasPhysRegs)
1092 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001093 MTM.SchedModel, MTM.TII, MTM.TRI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001094
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001095 // Update the required height of any virtual registers read by MI.
1096 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001097 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001098 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001099
1100 InstrCycles &MICycles = Cycles[MI];
1101 MICycles.Height = Cycle;
1102 if (!TBI.HasValidInstrDepths) {
1103 DEBUG(dbgs() << Cycle << '\t' << *MI);
1104 continue;
1105 }
1106 // Update critical path length.
1107 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1108 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001109 }
1110
1111 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1112 // height because the final height isn't known until now.
1113 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
1114 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1115 LiveInReg &LIR = TBI.LiveIns[i];
1116 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1117 LIR.Height = Heights.lookup(DefMI);
1118 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1119 }
1120
1121 // Transfer the live regunits to the live-in list.
1122 for (SparseSet<LiveRegUnit>::const_iterator
1123 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1124 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1125 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1126 << '@' << RI->Cycle);
1127 }
1128 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001129
1130 if (!TBI.HasValidInstrDepths)
1131 continue;
1132 // Add live-ins to the critical path length.
1133 TBI.CriticalPath = std::max(TBI.CriticalPath,
1134 computeCrossBlockCriticalPath(TBI));
1135 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001136 }
1137}
1138
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001139MachineTraceMetrics::Trace
1140MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1141 // FIXME: Check cache tags, recompute as needed.
1142 computeTrace(MBB);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001143 computeInstrDepths(MBB);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001144 computeInstrHeights(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001145 return Trace(*this, BlockInfo[MBB->getNumber()]);
1146}
1147
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001148unsigned
1149MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1150 assert(MI && "Not an instruction.");
1151 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1152 "MI must be in the trace center block");
1153 InstrCycles Cyc = getInstrCycles(MI);
1154 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1155}
1156
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001157unsigned
1158MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1159 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1160 SmallVector<DataDep, 1> Deps;
1161 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1162 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1163 DataDep &Dep = Deps.front();
1164 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1165 // Add latency if DefMI is a real instruction. Transients get latency 0.
1166 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001167 DepCycle += TE.MTM.SchedModel
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001168 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001169 return DepCycle;
1170}
1171
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001172unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001173 // Find the limiting processor resource.
1174 // Numbers have been pre-scaled to be comparable.
1175 unsigned PRMax = 0;
1176 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1177 if (Bottom) {
1178 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1179 for (unsigned K = 0; K != PRDepths.size(); ++K)
1180 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1181 } else {
1182 for (unsigned K = 0; K != PRDepths.size(); ++K)
1183 PRMax = std::max(PRMax, PRDepths[K]);
1184 }
1185 // Convert to cycle count.
1186 PRMax = TE.MTM.getCycles(PRMax);
1187
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001188 unsigned Instrs = TBI.InstrDepth;
1189 if (Bottom)
1190 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001191 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1192 Instrs /= IW;
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001193 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001194 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001195}
1196
Andrew Trick3aa53942013-04-27 03:54:20 +00001197
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001198unsigned MachineTraceMetrics::Trace::
Andrew Trick3aa53942013-04-27 03:54:20 +00001199getResourceLength(ArrayRef<const MachineBasicBlock*> Extrablocks,
1200 ArrayRef<const MCSchedClassDesc*> ExtraInstrs) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001201 // Add up resources above and below the center block.
1202 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1203 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1204 unsigned PRMax = 0;
1205 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1206 unsigned PRCycles = PRDepths[K] + PRHeights[K];
1207 for (unsigned I = 0; I != Extrablocks.size(); ++I)
1208 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
Andrew Trick3aa53942013-04-27 03:54:20 +00001209 for (unsigned I = 0; I != ExtraInstrs.size(); ++I) {
1210 const MCSchedClassDesc* SC = ExtraInstrs[I];
1211 if (!SC->isValid())
1212 continue;
1213 for (TargetSchedModel::ProcResIter
1214 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1215 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
1216 if (PI->ProcResourceIdx != K)
1217 continue;
1218 PRCycles += (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(K));
1219 }
1220 }
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001221 PRMax = std::max(PRMax, PRCycles);
1222 }
1223 // Convert to cycle count.
1224 PRMax = TE.MTM.getCycles(PRMax);
1225
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001226 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1227 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1228 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001229 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1230 Instrs /= IW;
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001231 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001232 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001233}
1234
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001235void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1236 OS << getName() << " ensemble:\n";
1237 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1238 OS << " BB#" << i << '\t';
1239 BlockInfo[i].print(OS);
1240 OS << '\n';
1241 }
1242}
1243
1244void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1245 if (hasValidDepth()) {
1246 OS << "depth=" << InstrDepth;
1247 if (Pred)
1248 OS << " pred=BB#" << Pred->getNumber();
1249 else
1250 OS << " pred=null";
1251 OS << " head=BB#" << Head;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001252 if (HasValidInstrDepths)
1253 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001254 } else
1255 OS << "depth invalid";
1256 OS << ", ";
1257 if (hasValidHeight()) {
1258 OS << "height=" << InstrHeight;
1259 if (Succ)
1260 OS << " succ=BB#" << Succ->getNumber();
1261 else
1262 OS << " succ=null";
1263 OS << " tail=BB#" << Tail;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001264 if (HasValidInstrHeights)
1265 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001266 } else
1267 OS << "height invalid";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001268 if (HasValidInstrDepths && HasValidInstrHeights)
1269 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001270}
1271
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001272void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001273 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1274
1275 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1276 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001277 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1278 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001279 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1280 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001281
1282 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001283 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001284 while (Block->hasValidDepth() && Block->Pred) {
1285 unsigned Num = Block->Pred->getNumber();
1286 OS << " <- BB#" << Num;
1287 Block = &TE.BlockInfo[Num];
1288 }
1289
1290 Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001291 OS << "\n ";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001292 while (Block->hasValidHeight() && Block->Succ) {
1293 unsigned Num = Block->Succ->getNumber();
1294 OS << " -> BB#" << Num;
1295 Block = &TE.BlockInfo[Num];
1296 }
1297 OS << '\n';
1298}