blob: 1da36b245a49f7cd97c790f55f19969d37978328 [file] [log] [blame]
Clement Courbet37f0ca02018-05-15 12:08:00 +00001//===-- Analysis.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
Clement Courbet37f0ca02018-05-15 12:08:00 +000010#include "Analysis.h"
Clement Courbeta66bfaa42018-05-15 13:07:05 +000011#include "BenchmarkResult.h"
Clement Courbetdf79e792018-06-01 14:18:02 +000012#include "llvm/ADT/STLExtras.h"
Clement Courbet4273e1e2018-06-15 07:30:45 +000013#include "llvm/MC/MCAsmInfo.h"
Clement Courbet37f0ca02018-05-15 12:08:00 +000014#include "llvm/Support/FormatVariadic.h"
Clement Courbet448550d2018-05-17 12:25:18 +000015#include <unordered_set>
Clement Courbet37f0ca02018-05-15 12:08:00 +000016#include <vector>
17
18namespace exegesis {
19
20static const char kCsvSep = ',';
21
Clement Courbet17d3c252018-05-22 13:31:29 +000022namespace {
23
Clement Courbet49fad1c2018-06-14 06:57:52 +000024enum EscapeTag { kEscapeCsv, kEscapeHtml, kEscapeHtmlString };
Clement Courbet17d3c252018-05-22 13:31:29 +000025
26template <EscapeTag Tag>
27void writeEscaped(llvm::raw_ostream &OS, const llvm::StringRef S);
28
29template <>
30void writeEscaped<kEscapeCsv>(llvm::raw_ostream &OS, const llvm::StringRef S) {
Clement Courbet37f0ca02018-05-15 12:08:00 +000031 if (std::find(S.begin(), S.end(), kCsvSep) == S.end()) {
32 OS << S;
33 } else {
34 // Needs escaping.
35 OS << '"';
36 for (const char C : S) {
37 if (C == '"')
38 OS << "\"\"";
39 else
40 OS << C;
41 }
42 OS << '"';
43 }
44}
45
Clement Courbet17d3c252018-05-22 13:31:29 +000046template <>
47void writeEscaped<kEscapeHtml>(llvm::raw_ostream &OS, const llvm::StringRef S) {
48 for (const char C : S) {
49 if (C == '<')
50 OS << "&lt;";
51 else if (C == '>')
52 OS << "&gt;";
53 else if (C == '&')
54 OS << "&amp;";
55 else
56 OS << C;
57 }
58}
59
Clement Courbet49fad1c2018-06-14 06:57:52 +000060template <>
Clement Courbet4273e1e2018-06-15 07:30:45 +000061void writeEscaped<kEscapeHtmlString>(llvm::raw_ostream &OS,
62 const llvm::StringRef S) {
Clement Courbet49fad1c2018-06-14 06:57:52 +000063 for (const char C : S) {
64 if (C == '"')
65 OS << "\\\"";
66 else
67 OS << C;
68 }
69}
70
Clement Courbet17d3c252018-05-22 13:31:29 +000071} // namespace
72
73template <EscapeTag Tag>
74static void
75writeClusterId(llvm::raw_ostream &OS,
76 const InstructionBenchmarkClustering::ClusterId &CID) {
77 if (CID.isNoise())
78 writeEscaped<Tag>(OS, "[noise]");
79 else if (CID.isError())
80 writeEscaped<Tag>(OS, "[error]");
81 else
82 OS << CID.getId();
83}
84
85template <EscapeTag Tag>
86static void writeMeasurementValue(llvm::raw_ostream &OS, const double Value) {
87 writeEscaped<Tag>(OS, llvm::formatv("{0:F}", Value).str());
88}
89
Clement Courbet4273e1e2018-06-15 07:30:45 +000090template <typename EscapeTag, EscapeTag Tag>
91void Analysis::writeSnippet(llvm::raw_ostream &OS,
92 llvm::ArrayRef<uint8_t> Bytes,
93 const char *Separator) const {
94 llvm::SmallVector<std::string, 3> Lines;
95 // Parse the asm snippet and print it.
96 while (!Bytes.empty()) {
97 llvm::MCInst MI;
98 uint64_t MISize = 0;
99 if (!Disasm_->getInstruction(MI, MISize, Bytes, 0, llvm::nulls(),
100 llvm::nulls())) {
101 writeEscaped<Tag>(OS, llvm::join(Lines, Separator));
102 writeEscaped<Tag>(OS, Separator);
103 writeEscaped<Tag>(OS, "[error decoding asm snippet]");
104 return;
105 }
106 Lines.emplace_back();
107 std::string &Line = Lines.back();
108 llvm::raw_string_ostream OSS(Line);
109 InstPrinter_->printInst(&MI, OSS, "", *SubtargetInfo_);
110 Bytes = Bytes.drop_front(MISize);
111 OSS.flush();
112 Line = llvm::StringRef(Line).trim().str();
Clement Courbet49fad1c2018-06-14 06:57:52 +0000113 }
Clement Courbet4273e1e2018-06-15 07:30:45 +0000114 writeEscaped<Tag>(OS, llvm::join(Lines, Separator));
Clement Courbet49fad1c2018-06-14 06:57:52 +0000115}
116
Clement Courbet37f0ca02018-05-15 12:08:00 +0000117// Prints a row representing an instruction, along with scheduling info and
118// point coordinates (measurements).
Clement Courbet17d3c252018-05-22 13:31:29 +0000119void Analysis::printInstructionRowCsv(const size_t PointId,
120 llvm::raw_ostream &OS) const {
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000121 const InstructionBenchmark &Point = Clustering_.getPoints()[PointId];
Clement Courbet17d3c252018-05-22 13:31:29 +0000122 writeClusterId<kEscapeCsv>(OS, Clustering_.getClusterIdForPoint(PointId));
Clement Courbet448550d2018-05-17 12:25:18 +0000123 OS << kCsvSep;
Clement Courbet4273e1e2018-06-15 07:30:45 +0000124 writeSnippet<EscapeTag, kEscapeCsv>(OS, Point.AssembledSnippet, "; ");
Clement Courbeta66bfaa42018-05-15 13:07:05 +0000125 OS << kCsvSep;
Clement Courbet17d3c252018-05-22 13:31:29 +0000126 writeEscaped<kEscapeCsv>(OS, Point.Key.Config);
127 OS << kCsvSep;
Clement Courbet49fad1c2018-06-14 06:57:52 +0000128 assert(!Point.Key.Instructions.empty());
129 // FIXME: Resolve variant classes.
130 const unsigned SchedClassId =
131 InstrInfo_->get(Point.Key.Instructions[0].getOpcode()).getSchedClass();
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000132#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Clement Courbet49fad1c2018-06-14 06:57:52 +0000133 const auto &SchedModel = SubtargetInfo_->getSchedModel();
134 const llvm::MCSchedClassDesc *const SCDesc =
135 SchedModel.getSchedClassDesc(SchedClassId);
136 writeEscaped<kEscapeCsv>(OS, SCDesc->Name);
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000137#else
Clement Courbet49fad1c2018-06-14 06:57:52 +0000138 OS << SchedClassId;
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000139#endif
Clement Courbet37f0ca02018-05-15 12:08:00 +0000140 for (const auto &Measurement : Point.Measurements) {
141 OS << kCsvSep;
Clement Courbet684a5f62018-09-26 08:37:21 +0000142 writeMeasurementValue<kEscapeCsv>(OS, Measurement.PerInstructionValue);
Clement Courbet37f0ca02018-05-15 12:08:00 +0000143 }
144 OS << "\n";
145}
146
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000147Analysis::Analysis(const llvm::Target &Target,
148 const InstructionBenchmarkClustering &Clustering)
149 : Clustering_(Clustering) {
150 if (Clustering.getPoints().empty())
151 return;
152
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000153 const InstructionBenchmark &FirstPoint = Clustering.getPoints().front();
Clement Courbet4273e1e2018-06-15 07:30:45 +0000154 InstrInfo_.reset(Target.createMCInstrInfo());
155 RegInfo_.reset(Target.createMCRegInfo(FirstPoint.LLVMTriple));
156 AsmInfo_.reset(Target.createMCAsmInfo(*RegInfo_, FirstPoint.LLVMTriple));
Clement Courbet448550d2018-05-17 12:25:18 +0000157 SubtargetInfo_.reset(Target.createMCSubtargetInfo(FirstPoint.LLVMTriple,
158 FirstPoint.CpuName, ""));
Clement Courbet4273e1e2018-06-15 07:30:45 +0000159 InstPrinter_.reset(Target.createMCInstPrinter(
160 llvm::Triple(FirstPoint.LLVMTriple), 0 /*default variant*/, *AsmInfo_,
161 *InstrInfo_, *RegInfo_));
162
163 Context_ = llvm::make_unique<llvm::MCContext>(AsmInfo_.get(), RegInfo_.get(),
164 &ObjectFileInfo_);
165 Disasm_.reset(Target.createMCDisassembler(*SubtargetInfo_, *Context_));
166 assert(Disasm_ && "cannot create MCDisassembler. missing call to "
167 "InitializeXXXTargetDisassembler ?");
Clement Courbet37f0ca02018-05-15 12:08:00 +0000168}
169
Clement Courbetcf210742018-05-17 13:41:28 +0000170template <>
171llvm::Error
172Analysis::run<Analysis::PrintClusters>(llvm::raw_ostream &OS) const {
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000173 if (Clustering_.getPoints().empty())
Clement Courbet37f0ca02018-05-15 12:08:00 +0000174 return llvm::Error::success();
175
176 // Write the header.
Clement Courbeta66bfaa42018-05-15 13:07:05 +0000177 OS << "cluster_id" << kCsvSep << "opcode_name" << kCsvSep << "config"
178 << kCsvSep << "sched_class";
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000179 for (const auto &Measurement : Clustering_.getPoints().front().Measurements) {
Clement Courbet37f0ca02018-05-15 12:08:00 +0000180 OS << kCsvSep;
Clement Courbet17d3c252018-05-22 13:31:29 +0000181 writeEscaped<kEscapeCsv>(OS, Measurement.Key);
Clement Courbet37f0ca02018-05-15 12:08:00 +0000182 }
183 OS << "\n";
184
185 // Write the points.
Clement Courbet448550d2018-05-17 12:25:18 +0000186 const auto &Clusters = Clustering_.getValidClusters();
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000187 for (size_t I = 0, E = Clusters.size(); I < E; ++I) {
188 for (const size_t PointId : Clusters[I].PointIndices) {
Clement Courbet17d3c252018-05-22 13:31:29 +0000189 printInstructionRowCsv(PointId, OS);
Clement Courbet6d6c1a92018-05-16 08:47:21 +0000190 }
Clement Courbet37f0ca02018-05-15 12:08:00 +0000191 OS << "\n\n";
192 }
193 return llvm::Error::success();
194}
195
Clement Courbet448550d2018-05-17 12:25:18 +0000196std::unordered_map<unsigned, std::vector<size_t>>
197Analysis::makePointsPerSchedClass() const {
198 std::unordered_map<unsigned, std::vector<size_t>> PointsPerSchedClass;
199 const auto &Points = Clustering_.getPoints();
200 for (size_t PointId = 0, E = Points.size(); PointId < E; ++PointId) {
201 const InstructionBenchmark &Point = Points[PointId];
202 if (!Point.Error.empty())
203 continue;
Clement Courbet49fad1c2018-06-14 06:57:52 +0000204 assert(!Point.Key.Instructions.empty());
205 const auto Opcode = Point.Key.Instructions[0].getOpcode();
206 // FIXME: Resolve variant classes.
207 PointsPerSchedClass[InstrInfo_->get(Opcode).getSchedClass()].push_back(
208 PointId);
Clement Courbet448550d2018-05-17 12:25:18 +0000209 }
210 return PointsPerSchedClass;
211}
212
Clement Courbet49fad1c2018-06-14 06:57:52 +0000213// Uops repeat the same opcode over again. Just show this opcode and show the
214// whole snippet only on hover.
215static void writeUopsSnippetHtml(llvm::raw_ostream &OS,
216 const std::vector<llvm::MCInst> &Instructions,
217 const llvm::MCInstrInfo &InstrInfo) {
218 if (Instructions.empty())
219 return;
220 writeEscaped<kEscapeHtml>(OS, InstrInfo.getName(Instructions[0].getOpcode()));
221 if (Instructions.size() > 1)
222 OS << " (x" << Instructions.size() << ")";
223}
224
225// Latency tries to find a serial path. Just show the opcode path and show the
226// whole snippet only on hover.
Clement Courbet4273e1e2018-06-15 07:30:45 +0000227static void
228writeLatencySnippetHtml(llvm::raw_ostream &OS,
229 const std::vector<llvm::MCInst> &Instructions,
230 const llvm::MCInstrInfo &InstrInfo) {
Clement Courbet49fad1c2018-06-14 06:57:52 +0000231 bool First = true;
232 for (const llvm::MCInst &Instr : Instructions) {
233 if (First)
234 First = false;
235 else
236 OS << " &rarr; ";
237 writeEscaped<kEscapeHtml>(OS, InstrInfo.getName(Instr.getOpcode()));
238 }
239}
240
Clement Courbet72287212018-06-04 11:11:55 +0000241void Analysis::printSchedClassClustersHtml(
242 const std::vector<SchedClassCluster> &Clusters, const SchedClass &SC,
243 llvm::raw_ostream &OS) const {
Clement Courbet17d3c252018-05-22 13:31:29 +0000244 const auto &Points = Clustering_.getPoints();
Clement Courbet2637e5f2018-05-24 10:47:05 +0000245 OS << "<table class=\"sched-class-clusters\">";
Clement Courbet17d3c252018-05-22 13:31:29 +0000246 OS << "<tr><th>ClusterId</th><th>Opcode/Config</th>";
Clement Courbet72287212018-06-04 11:11:55 +0000247 assert(!Clusters.empty());
248 for (const auto &Measurement :
249 Points[Clusters[0].getPointIds()[0]].Measurements) {
Clement Courbet17d3c252018-05-22 13:31:29 +0000250 OS << "<th>";
Clement Courbet28d4f852018-09-26 13:35:10 +0000251 writeEscaped<kEscapeHtml>(OS, Measurement.Key);
Clement Courbet17d3c252018-05-22 13:31:29 +0000252 OS << "</th>";
253 }
254 OS << "</tr>";
Clement Courbet72287212018-06-04 11:11:55 +0000255 for (const SchedClassCluster &Cluster : Clusters) {
256 OS << "<tr class=\""
257 << (Cluster.measurementsMatch(*SubtargetInfo_, SC, Clustering_)
258 ? "good-cluster"
259 : "bad-cluster")
260 << "\"><td>";
261 writeClusterId<kEscapeHtml>(OS, Cluster.id());
Clement Courbet17d3c252018-05-22 13:31:29 +0000262 OS << "</td><td><ul>";
Clement Courbet72287212018-06-04 11:11:55 +0000263 for (const size_t PointId : Cluster.getPointIds()) {
264 const auto &Point = Points[PointId];
Clement Courbet49fad1c2018-06-14 06:57:52 +0000265 OS << "<li><span class=\"mono\" title=\"";
Clement Courbet4273e1e2018-06-15 07:30:45 +0000266 writeSnippet<EscapeTag, kEscapeHtmlString>(OS, Point.AssembledSnippet,
267 "\n");
Clement Courbet49fad1c2018-06-14 06:57:52 +0000268 OS << "\">";
269 switch (Point.Mode) {
Clement Courbet4273e1e2018-06-15 07:30:45 +0000270 case InstructionBenchmark::Latency:
271 writeLatencySnippetHtml(OS, Point.Key.Instructions, *InstrInfo_);
272 break;
273 case InstructionBenchmark::Uops:
274 writeUopsSnippetHtml(OS, Point.Key.Instructions, *InstrInfo_);
275 break;
276 default:
277 llvm_unreachable("invalid mode");
Clement Courbet49fad1c2018-06-14 06:57:52 +0000278 }
Clement Courbet17d3c252018-05-22 13:31:29 +0000279 OS << "</span> <span class=\"mono\">";
Clement Courbetae8ae5dc2018-05-24 12:41:02 +0000280 writeEscaped<kEscapeHtml>(OS, Point.Key.Config);
Clement Courbet17d3c252018-05-22 13:31:29 +0000281 OS << "</span></li>";
282 }
283 OS << "</ul></td>";
Clement Courbet72287212018-06-04 11:11:55 +0000284 for (const auto &Stats : Cluster.getRepresentative()) {
Clement Courbetae8ae5dc2018-05-24 12:41:02 +0000285 OS << "<td class=\"measurement\">";
286 writeMeasurementValue<kEscapeHtml>(OS, Stats.avg());
287 OS << "<br><span class=\"minmax\">[";
288 writeMeasurementValue<kEscapeHtml>(OS, Stats.min());
289 OS << ";";
290 writeMeasurementValue<kEscapeHtml>(OS, Stats.max());
291 OS << "]</span></td>";
Clement Courbet17d3c252018-05-22 13:31:29 +0000292 }
293 OS << "</tr>";
294 }
295 OS << "</table>";
296}
297
Clement Courbet2637e5f2018-05-24 10:47:05 +0000298// Return the non-redundant list of WriteProcRes used by the given sched class.
299// The scheduling model for LLVM is such that each instruction has a certain
300// number of uops which consume resources which are described by WriteProcRes
301// entries. Each entry describe how many cycles are spent on a specific ProcRes
302// kind.
303// For example, an instruction might have 3 uOps, one dispatching on P0
304// (ProcResIdx=1) and two on P06 (ProcResIdx = 7).
305// Note that LLVM additionally denormalizes resource consumption to include
306// usage of super resources by subresources. So in practice if there exists a
307// P016 (ProcResIdx=10), then the cycles consumed by P0 are also consumed by
308// P06 (ProcResIdx = 7) and P016 (ProcResIdx = 10), and the resources consumed
309// by P06 are also consumed by P016. In the figure below, parenthesized cycles
310// denote implied usage of superresources by subresources:
311// P0 P06 P016
312// uOp1 1 (1) (1)
313// uOp2 1 (1)
314// uOp3 1 (1)
315// =============================
316// 1 3 3
317// Eventually we end up with three entries for the WriteProcRes of the
318// instruction:
319// {ProcResIdx=1, Cycles=1} // P0
320// {ProcResIdx=7, Cycles=3} // P06
321// {ProcResIdx=10, Cycles=3} // P016
322//
323// Note that in this case, P016 does not contribute any cycles, so it would
324// be removed by this function.
325// FIXME: Move this to MCSubtargetInfo and use it in llvm-mca.
326static llvm::SmallVector<llvm::MCWriteProcResEntry, 8>
327getNonRedundantWriteProcRes(const llvm::MCSchedClassDesc &SCDesc,
328 const llvm::MCSubtargetInfo &STI) {
329 llvm::SmallVector<llvm::MCWriteProcResEntry, 8> Result;
330 const auto &SM = STI.getSchedModel();
331 const unsigned NumProcRes = SM.getNumProcResourceKinds();
332
333 // This assumes that the ProcResDescs are sorted in topological order, which
334 // is guaranteed by the tablegen backend.
335 llvm::SmallVector<float, 32> ProcResUnitUsage(NumProcRes);
336 for (const auto *WPR = STI.getWriteProcResBegin(&SCDesc),
337 *const WPREnd = STI.getWriteProcResEnd(&SCDesc);
338 WPR != WPREnd; ++WPR) {
339 const llvm::MCProcResourceDesc *const ProcResDesc =
340 SM.getProcResource(WPR->ProcResourceIdx);
341 if (ProcResDesc->SubUnitsIdxBegin == nullptr) {
342 // This is a ProcResUnit.
343 Result.push_back({WPR->ProcResourceIdx, WPR->Cycles});
344 ProcResUnitUsage[WPR->ProcResourceIdx] += WPR->Cycles;
345 } else {
346 // This is a ProcResGroup. First see if it contributes any cycles or if
347 // it has cycles just from subunits.
348 float RemainingCycles = WPR->Cycles;
349 for (const auto *SubResIdx = ProcResDesc->SubUnitsIdxBegin;
350 SubResIdx != ProcResDesc->SubUnitsIdxBegin + ProcResDesc->NumUnits;
351 ++SubResIdx) {
352 RemainingCycles -= ProcResUnitUsage[*SubResIdx];
353 }
354 if (RemainingCycles < 0.01f) {
355 // The ProcResGroup contributes no cycles of its own.
356 continue;
357 }
358 // The ProcResGroup contributes `RemainingCycles` cycles of its own.
359 Result.push_back({WPR->ProcResourceIdx,
360 static_cast<uint16_t>(std::round(RemainingCycles))});
361 // Spread the remaining cycles over all subunits.
362 for (const auto *SubResIdx = ProcResDesc->SubUnitsIdxBegin;
363 SubResIdx != ProcResDesc->SubUnitsIdxBegin + ProcResDesc->NumUnits;
364 ++SubResIdx) {
365 ProcResUnitUsage[*SubResIdx] += RemainingCycles / ProcResDesc->NumUnits;
366 }
367 }
368 }
369 return Result;
370}
371
Clement Courbet72287212018-06-04 11:11:55 +0000372Analysis::SchedClass::SchedClass(const llvm::MCSchedClassDesc &SD,
373 const llvm::MCSubtargetInfo &STI)
Clement Courbet4273e1e2018-06-15 07:30:45 +0000374 : SCDesc(&SD),
Clement Courbet72287212018-06-04 11:11:55 +0000375 NonRedundantWriteProcRes(getNonRedundantWriteProcRes(SD, STI)),
376 IdealizedProcResPressure(computeIdealizedProcResPressure(
377 STI.getSchedModel(), NonRedundantWriteProcRes)) {}
378
379void Analysis::SchedClassCluster::addPoint(
380 size_t PointId, const InstructionBenchmarkClustering &Clustering) {
381 PointIds.push_back(PointId);
382 const auto &Point = Clustering.getPoints()[PointId];
383 if (ClusterId.isUndef()) {
384 ClusterId = Clustering.getClusterIdForPoint(PointId);
385 Representative.resize(Point.Measurements.size());
386 }
387 for (size_t I = 0, E = Point.Measurements.size(); I < E; ++I) {
388 Representative[I].push(Point.Measurements[I]);
389 }
390 assert(ClusterId == Clustering.getClusterIdForPoint(PointId));
391}
392
393bool Analysis::SchedClassCluster::measurementsMatch(
394 const llvm::MCSubtargetInfo &STI, const SchedClass &SC,
395 const InstructionBenchmarkClustering &Clustering) const {
396 const size_t NumMeasurements = Representative.size();
397 std::vector<BenchmarkMeasure> ClusterCenterPoint(NumMeasurements);
398 std::vector<BenchmarkMeasure> SchedClassPoint(NumMeasurements);
399 // Latency case.
400 assert(!Clustering.getPoints().empty());
Clement Courbet62b34fa2018-06-06 09:42:36 +0000401 const InstructionBenchmark::ModeE Mode = Clustering.getPoints()[0].Mode;
402 if (Mode == InstructionBenchmark::Latency) {
Clement Courbet72287212018-06-04 11:11:55 +0000403 if (NumMeasurements != 1) {
404 llvm::errs()
405 << "invalid number of measurements in latency mode: expected 1, got "
406 << NumMeasurements << "\n";
407 return false;
408 }
409 // Find the latency.
Clement Courbet684a5f62018-09-26 08:37:21 +0000410 SchedClassPoint[0].PerInstructionValue = 0.0;
Clement Courbet4273e1e2018-06-15 07:30:45 +0000411 for (unsigned I = 0; I < SC.SCDesc->NumWriteLatencyEntries; ++I) {
Clement Courbet72287212018-06-04 11:11:55 +0000412 const llvm::MCWriteLatencyEntry *const WLE =
Clement Courbet4273e1e2018-06-15 07:30:45 +0000413 STI.getWriteLatencyEntry(SC.SCDesc, I);
Clement Courbet684a5f62018-09-26 08:37:21 +0000414 SchedClassPoint[0].PerInstructionValue =
415 std::max<double>(SchedClassPoint[0].PerInstructionValue, WLE->Cycles);
Clement Courbet72287212018-06-04 11:11:55 +0000416 }
Clement Courbet684a5f62018-09-26 08:37:21 +0000417 ClusterCenterPoint[0].PerInstructionValue = Representative[0].avg();
Clement Courbet62b34fa2018-06-06 09:42:36 +0000418 } else if (Mode == InstructionBenchmark::Uops) {
Clement Courbet72287212018-06-04 11:11:55 +0000419 for (int I = 0, E = Representative.size(); I < E; ++I) {
420 // Find the pressure on ProcResIdx `Key`.
421 uint16_t ProcResIdx = 0;
422 if (!llvm::to_integer(Representative[I].key(), ProcResIdx, 10)) {
423 llvm::errs() << "expected ProcResIdx key, got "
424 << Representative[I].key() << "\n";
425 return false;
426 }
427 const auto ProcResPressureIt =
428 std::find_if(SC.IdealizedProcResPressure.begin(),
429 SC.IdealizedProcResPressure.end(),
430 [ProcResIdx](const std::pair<uint16_t, float> &WPR) {
431 return WPR.first == ProcResIdx;
432 });
Clement Courbet684a5f62018-09-26 08:37:21 +0000433 SchedClassPoint[I].PerInstructionValue =
Clement Courbet72287212018-06-04 11:11:55 +0000434 ProcResPressureIt == SC.IdealizedProcResPressure.end()
435 ? 0.0
436 : ProcResPressureIt->second;
Clement Courbet684a5f62018-09-26 08:37:21 +0000437 ClusterCenterPoint[I].PerInstructionValue = Representative[I].avg();
Clement Courbet72287212018-06-04 11:11:55 +0000438 }
439 } else {
Clement Courbet2cb97b92018-06-04 11:43:40 +0000440 llvm::errs() << "unimplemented measurement matching for mode " << Mode
441 << "\n";
Clement Courbet72287212018-06-04 11:11:55 +0000442 return false;
443 }
444 return Clustering.isNeighbour(ClusterCenterPoint, SchedClassPoint);
445}
446
447void Analysis::printSchedClassDescHtml(const SchedClass &SC,
Clement Courbet2637e5f2018-05-24 10:47:05 +0000448 llvm::raw_ostream &OS) const {
449 OS << "<table class=\"sched-class-desc\">";
450 OS << "<tr><th>Valid</th><th>Variant</th><th>uOps</th><th>Latency</"
Clement Courbetdf79e792018-06-01 14:18:02 +0000451 "th><th>WriteProcRes</th><th title=\"This is the idealized unit "
452 "resource (port) pressure assuming ideal distribution\">Idealized "
453 "Resource Pressure</th></tr>";
Clement Courbet4273e1e2018-06-15 07:30:45 +0000454 if (SC.SCDesc->isValid()) {
Clement Courbetdf79e792018-06-01 14:18:02 +0000455 const auto &SM = SubtargetInfo_->getSchedModel();
Clement Courbet2637e5f2018-05-24 10:47:05 +0000456 OS << "<tr><td>&#10004;</td>";
Clement Courbet4273e1e2018-06-15 07:30:45 +0000457 OS << "<td>" << (SC.SCDesc->isVariant() ? "&#10004;" : "&#10005;")
Clement Courbet72287212018-06-04 11:11:55 +0000458 << "</td>";
Clement Courbet4273e1e2018-06-15 07:30:45 +0000459 OS << "<td>" << SC.SCDesc->NumMicroOps << "</td>";
Clement Courbet2637e5f2018-05-24 10:47:05 +0000460 // Latencies.
461 OS << "<td><ul>";
Clement Courbet4273e1e2018-06-15 07:30:45 +0000462 for (int I = 0, E = SC.SCDesc->NumWriteLatencyEntries; I < E; ++I) {
Clement Courbet2637e5f2018-05-24 10:47:05 +0000463 const auto *const Entry =
Clement Courbet4273e1e2018-06-15 07:30:45 +0000464 SubtargetInfo_->getWriteLatencyEntry(SC.SCDesc, I);
Clement Courbet2637e5f2018-05-24 10:47:05 +0000465 OS << "<li>" << Entry->Cycles;
Clement Courbet4273e1e2018-06-15 07:30:45 +0000466 if (SC.SCDesc->NumWriteLatencyEntries > 1) {
Clement Courbet2637e5f2018-05-24 10:47:05 +0000467 // Dismabiguate if more than 1 latency.
468 OS << " (WriteResourceID " << Entry->WriteResourceID << ")";
469 }
470 OS << "</li>";
471 }
472 OS << "</ul></td>";
473 // WriteProcRes.
474 OS << "<td><ul>";
Clement Courbet72287212018-06-04 11:11:55 +0000475 for (const auto &WPR : SC.NonRedundantWriteProcRes) {
Clement Courbetdf79e792018-06-01 14:18:02 +0000476 OS << "<li><span class=\"mono\">";
477 writeEscaped<kEscapeHtml>(OS,
478 SM.getProcResource(WPR.ProcResourceIdx)->Name);
479 OS << "</span>: " << WPR.Cycles << "</li>";
480 }
481 OS << "</ul></td>";
482 // Idealized port pressure.
483 OS << "<td><ul>";
Clement Courbet72287212018-06-04 11:11:55 +0000484 for (const auto &Pressure : SC.IdealizedProcResPressure) {
Clement Courbet2637e5f2018-05-24 10:47:05 +0000485 OS << "<li><span class=\"mono\">";
486 writeEscaped<kEscapeHtml>(OS, SubtargetInfo_->getSchedModel()
Clement Courbetdf79e792018-06-01 14:18:02 +0000487 .getProcResource(Pressure.first)
Clement Courbet2637e5f2018-05-24 10:47:05 +0000488 ->Name);
Clement Courbetdf79e792018-06-01 14:18:02 +0000489 OS << "</span>: ";
490 writeMeasurementValue<kEscapeHtml>(OS, Pressure.second);
491 OS << "</li>";
Clement Courbet2637e5f2018-05-24 10:47:05 +0000492 }
493 OS << "</ul></td>";
494 OS << "</tr>";
495 } else {
496 OS << "<tr><td>&#10005;</td><td></td><td></td></tr>";
497 }
498 OS << "</table>";
499}
500
Clement Courbet17d3c252018-05-22 13:31:29 +0000501static constexpr const char kHtmlHead[] = R"(
502<head>
503<title>llvm-exegesis Analysis Results</title>
504<style>
505body {
506 font-family: sans-serif
507}
508span.sched-class-name {
509 font-weight: bold;
510 font-family: monospace;
511}
512span.opcode {
513 font-family: monospace;
514}
515span.config {
516 font-family: monospace;
517}
518div.inconsistency {
519 margin-top: 50px;
520}
Clement Courbet2637e5f2018-05-24 10:47:05 +0000521table {
Clement Courbet17d3c252018-05-22 13:31:29 +0000522 margin-left: 50px;
523 border-collapse: collapse;
524}
Clement Courbet2637e5f2018-05-24 10:47:05 +0000525table, table tr,td,th {
Clement Courbet17d3c252018-05-22 13:31:29 +0000526 border: 1px solid #444;
527}
Clement Courbet2637e5f2018-05-24 10:47:05 +0000528table ul {
529 padding-left: 0px;
530 margin: 0px;
531 list-style-type: none;
532}
533table.sched-class-clusters td {
Clement Courbet17d3c252018-05-22 13:31:29 +0000534 padding-left: 10px;
535 padding-right: 10px;
536 padding-top: 10px;
537 padding-bottom: 10px;
538}
Clement Courbet2637e5f2018-05-24 10:47:05 +0000539table.sched-class-desc td {
540 padding-left: 10px;
541 padding-right: 10px;
542 padding-top: 2px;
543 padding-bottom: 2px;
Clement Courbet17d3c252018-05-22 13:31:29 +0000544}
545span.mono {
546 font-family: monospace;
547}
Clement Courbetae8ae5dc2018-05-24 12:41:02 +0000548td.measurement {
549 text-align: center;
550}
Clement Courbet72287212018-06-04 11:11:55 +0000551tr.good-cluster td.measurement {
552 color: #292
553}
554tr.bad-cluster td.measurement {
555 color: #922
556}
557tr.good-cluster td.measurement span.minmax {
558 color: #888;
559}
560tr.bad-cluster td.measurement span.minmax {
561 color: #888;
562}
Clement Courbet17d3c252018-05-22 13:31:29 +0000563</style>
564</head>
565)";
566
Clement Courbetcf210742018-05-17 13:41:28 +0000567template <>
568llvm::Error Analysis::run<Analysis::PrintSchedClassInconsistencies>(
569 llvm::raw_ostream &OS) const {
Clement Courbet72287212018-06-04 11:11:55 +0000570 const auto &FirstPoint = Clustering_.getPoints()[0];
Clement Courbet17d3c252018-05-22 13:31:29 +0000571 // Print the header.
572 OS << "<!DOCTYPE html><html>" << kHtmlHead << "<body>";
573 OS << "<h1><span class=\"mono\">llvm-exegesis</span> Analysis Results</h1>";
574 OS << "<h3>Triple: <span class=\"mono\">";
Clement Courbet72287212018-06-04 11:11:55 +0000575 writeEscaped<kEscapeHtml>(OS, FirstPoint.LLVMTriple);
Clement Courbet17d3c252018-05-22 13:31:29 +0000576 OS << "</span></h3><h3>Cpu: <span class=\"mono\">";
Clement Courbet72287212018-06-04 11:11:55 +0000577 writeEscaped<kEscapeHtml>(OS, FirstPoint.CpuName);
Clement Courbet17d3c252018-05-22 13:31:29 +0000578 OS << "</span></h3>";
579
Clement Courbet448550d2018-05-17 12:25:18 +0000580 for (const auto &SchedClassAndPoints : makePointsPerSchedClass()) {
Clement Courbet72287212018-06-04 11:11:55 +0000581 const auto SchedClassId = SchedClassAndPoints.first;
582 const std::vector<size_t> &SchedClassPoints = SchedClassAndPoints.second;
Clement Courbet448550d2018-05-17 12:25:18 +0000583 const auto &SchedModel = SubtargetInfo_->getSchedModel();
584 const llvm::MCSchedClassDesc *const SCDesc =
Clement Courbet72287212018-06-04 11:11:55 +0000585 SchedModel.getSchedClassDesc(SchedClassId);
Clement Courbet2637e5f2018-05-24 10:47:05 +0000586 if (!SCDesc)
587 continue;
Clement Courbet72287212018-06-04 11:11:55 +0000588 const SchedClass SC(*SCDesc, *SubtargetInfo_);
589
590 // Bucket sched class points into sched class clusters.
591 std::vector<SchedClassCluster> SchedClassClusters;
592 for (const size_t PointId : SchedClassPoints) {
593 const auto &ClusterId = Clustering_.getClusterIdForPoint(PointId);
594 if (!ClusterId.isValid())
595 continue; // Ignore noise and errors. FIXME: take noise into account ?
596 auto SchedClassClusterIt =
597 std::find_if(SchedClassClusters.begin(), SchedClassClusters.end(),
598 [ClusterId](const SchedClassCluster &C) {
599 return C.id() == ClusterId;
600 });
601 if (SchedClassClusterIt == SchedClassClusters.end()) {
602 SchedClassClusters.emplace_back();
603 SchedClassClusterIt = std::prev(SchedClassClusters.end());
604 }
605 SchedClassClusterIt->addPoint(PointId, Clustering_);
606 }
607
608 // Print any scheduling class that has at least one cluster that does not
609 // match the checked-in data.
610 if (std::all_of(SchedClassClusters.begin(), SchedClassClusters.end(),
611 [this, &SC](const SchedClassCluster &C) {
612 return C.measurementsMatch(*SubtargetInfo_, SC,
613 Clustering_);
614 }))
615 continue; // Nothing weird.
616
Clement Courbet2637e5f2018-05-24 10:47:05 +0000617 OS << "<div class=\"inconsistency\"><p>Sched Class <span "
618 "class=\"sched-class-name\">";
619#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Clement Courbet17d3c252018-05-22 13:31:29 +0000620 writeEscaped<kEscapeHtml>(OS, SCDesc->Name);
Clement Courbet448550d2018-05-17 12:25:18 +0000621#else
Clement Courbet72287212018-06-04 11:11:55 +0000622 OS << SchedClassId;
Clement Courbet448550d2018-05-17 12:25:18 +0000623#endif
Clement Courbet72287212018-06-04 11:11:55 +0000624 OS << "</span> contains instructions whose performance characteristics do"
625 " not match that of LLVM:</p>";
626 printSchedClassClustersHtml(SchedClassClusters, SC, OS);
627 OS << "<p>llvm SchedModel data:</p>";
628 printSchedClassDescHtml(SC, OS);
Clement Courbet17d3c252018-05-22 13:31:29 +0000629 OS << "</div>";
Clement Courbet448550d2018-05-17 12:25:18 +0000630 }
Clement Courbet17d3c252018-05-22 13:31:29 +0000631
632 OS << "</body></html>";
Clement Courbet448550d2018-05-17 12:25:18 +0000633 return llvm::Error::success();
634}
635
Clement Courbetdf79e792018-06-01 14:18:02 +0000636// Distributes a pressure budget as evenly as possible on the provided subunits
637// given the already existing port pressure distribution.
638//
639// The algorithm is as follows: while there is remaining pressure to
640// distribute, find the subunits with minimal pressure, and distribute
641// remaining pressure equally up to the pressure of the unit with
642// second-to-minimal pressure.
643// For example, let's assume we want to distribute 2*P1256
644// (Subunits = [P1,P2,P5,P6]), and the starting DensePressure is:
645// DensePressure = P0 P1 P2 P3 P4 P5 P6 P7
646// 0.1 0.3 0.2 0.0 0.0 0.5 0.5 0.5
647// RemainingPressure = 2.0
648// We sort the subunits by pressure:
649// Subunits = [(P2,p=0.2), (P1,p=0.3), (P5,p=0.5), (P6, p=0.5)]
650// We'll first start by the subunits with minimal pressure, which are at
651// the beginning of the sorted array. In this example there is one (P2).
652// The subunit with second-to-minimal pressure is the next one in the
653// array (P1). So we distribute 0.1 pressure to P2, and remove 0.1 cycles
654// from the budget.
655// Subunits = [(P2,p=0.3), (P1,p=0.3), (P5,p=0.5), (P5,p=0.5)]
656// RemainingPressure = 1.9
657// We repeat this process: distribute 0.2 pressure on each of the minimal
658// P2 and P1, decrease budget by 2*0.2:
659// Subunits = [(P2,p=0.5), (P1,p=0.5), (P5,p=0.5), (P5,p=0.5)]
660// RemainingPressure = 1.5
661// There are no second-to-minimal subunits so we just share the remaining
662// budget (1.5 cycles) equally:
663// Subunits = [(P2,p=0.875), (P1,p=0.875), (P5,p=0.875), (P5,p=0.875)]
664// RemainingPressure = 0.0
665// We stop as there is no remaining budget to distribute.
666void distributePressure(float RemainingPressure,
667 llvm::SmallVector<uint16_t, 32> Subunits,
668 llvm::SmallVector<float, 32> &DensePressure) {
669 // Find the number of subunits with minimal pressure (they are at the
670 // front).
671 llvm::sort(Subunits.begin(), Subunits.end(),
672 [&DensePressure](const uint16_t A, const uint16_t B) {
673 return DensePressure[A] < DensePressure[B];
674 });
675 const auto getPressureForSubunit = [&DensePressure,
676 &Subunits](size_t I) -> float & {
677 return DensePressure[Subunits[I]];
678 };
679 size_t NumMinimalSU = 1;
680 while (NumMinimalSU < Subunits.size() &&
681 getPressureForSubunit(NumMinimalSU) == getPressureForSubunit(0)) {
682 ++NumMinimalSU;
683 }
684 while (RemainingPressure > 0.0f) {
685 if (NumMinimalSU == Subunits.size()) {
686 // All units are minimal, just distribute evenly and be done.
687 for (size_t I = 0; I < NumMinimalSU; ++I) {
688 getPressureForSubunit(I) += RemainingPressure / NumMinimalSU;
689 }
690 return;
691 }
692 // Distribute the remaining pressure equally.
693 const float MinimalPressure = getPressureForSubunit(NumMinimalSU - 1);
694 const float SecondToMinimalPressure = getPressureForSubunit(NumMinimalSU);
695 assert(MinimalPressure < SecondToMinimalPressure);
696 const float Increment = SecondToMinimalPressure - MinimalPressure;
697 if (RemainingPressure <= NumMinimalSU * Increment) {
698 // There is not enough remaining pressure.
699 for (size_t I = 0; I < NumMinimalSU; ++I) {
700 getPressureForSubunit(I) += RemainingPressure / NumMinimalSU;
701 }
702 return;
703 }
704 // Bump all minimal pressure subunits to `SecondToMinimalPressure`.
705 for (size_t I = 0; I < NumMinimalSU; ++I) {
706 getPressureForSubunit(I) = SecondToMinimalPressure;
707 RemainingPressure -= SecondToMinimalPressure;
708 }
709 while (NumMinimalSU < Subunits.size() &&
710 getPressureForSubunit(NumMinimalSU) == SecondToMinimalPressure) {
711 ++NumMinimalSU;
712 }
713 }
714}
715
716std::vector<std::pair<uint16_t, float>> computeIdealizedProcResPressure(
717 const llvm::MCSchedModel &SM,
718 llvm::SmallVector<llvm::MCWriteProcResEntry, 8> WPRS) {
719 // DensePressure[I] is the port pressure for Proc Resource I.
720 llvm::SmallVector<float, 32> DensePressure(SM.getNumProcResourceKinds());
721 llvm::sort(WPRS.begin(), WPRS.end(),
722 [](const llvm::MCWriteProcResEntry &A,
723 const llvm::MCWriteProcResEntry &B) {
724 return A.ProcResourceIdx < B.ProcResourceIdx;
725 });
726 for (const llvm::MCWriteProcResEntry &WPR : WPRS) {
727 // Get units for the entry.
728 const llvm::MCProcResourceDesc *const ProcResDesc =
729 SM.getProcResource(WPR.ProcResourceIdx);
730 if (ProcResDesc->SubUnitsIdxBegin == nullptr) {
731 // This is a ProcResUnit.
732 DensePressure[WPR.ProcResourceIdx] += WPR.Cycles;
733 } else {
734 // This is a ProcResGroup.
735 llvm::SmallVector<uint16_t, 32> Subunits(ProcResDesc->SubUnitsIdxBegin,
736 ProcResDesc->SubUnitsIdxBegin +
737 ProcResDesc->NumUnits);
738 distributePressure(WPR.Cycles, Subunits, DensePressure);
739 }
740 }
741 // Turn dense pressure into sparse pressure by removing zero entries.
742 std::vector<std::pair<uint16_t, float>> Pressure;
743 for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I) {
744 if (DensePressure[I] > 0.0f)
745 Pressure.emplace_back(I, DensePressure[I]);
746 }
747 return Pressure;
748}
749
Clement Courbet37f0ca02018-05-15 12:08:00 +0000750} // namespace exegesis