1 //===-- Analysis.cpp --------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 #include "BenchmarkResult.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/MC/MCTargetOptions.h"
14 #include "llvm/Support/FormatVariadic.h"
16 #include <unordered_set>
22 static const char kCsvSep
= ',';
26 enum EscapeTag
{ kEscapeCsv
, kEscapeHtml
, kEscapeHtmlString
};
28 template <EscapeTag Tag
> void writeEscaped(raw_ostream
&OS
, const StringRef S
);
30 template <> void writeEscaped
<kEscapeCsv
>(raw_ostream
&OS
, const StringRef S
) {
31 if (!llvm::is_contained(S
, kCsvSep
)) {
36 for (const char C
: S
) {
46 template <> void writeEscaped
<kEscapeHtml
>(raw_ostream
&OS
, const StringRef S
) {
47 for (const char C
: S
) {
60 void writeEscaped
<kEscapeHtmlString
>(raw_ostream
&OS
, const StringRef S
) {
61 for (const char C
: S
) {
71 template <EscapeTag Tag
>
73 writeClusterId(raw_ostream
&OS
,
74 const InstructionBenchmarkClustering::ClusterId
&CID
) {
76 writeEscaped
<Tag
>(OS
, "[noise]");
77 else if (CID
.isError())
78 writeEscaped
<Tag
>(OS
, "[error]");
83 template <EscapeTag Tag
>
84 static void writeMeasurementValue(raw_ostream
&OS
, const double Value
) {
85 // Given Value, if we wanted to serialize it to a string,
86 // how many base-10 digits will we need to store, max?
87 static constexpr auto MaxDigitCount
=
88 std::numeric_limits
<decltype(Value
)>::max_digits10
;
89 // Also, we will need a decimal separator.
90 static constexpr auto DecimalSeparatorLen
= 1; // '.' e.g.
91 // So how long of a string will the serialization produce, max?
92 static constexpr auto SerializationLen
= MaxDigitCount
+ DecimalSeparatorLen
;
94 // WARNING: when changing the format, also adjust the small-size estimate ^.
95 static constexpr StringLiteral SimpleFloatFormat
= StringLiteral("{0:F}");
98 OS
, formatv(SimpleFloatFormat
.data(), Value
).sstr
<SerializationLen
>());
101 template <typename EscapeTag
, EscapeTag Tag
>
102 void Analysis::writeSnippet(raw_ostream
&OS
, ArrayRef
<uint8_t> Bytes
,
103 const char *Separator
) const {
104 SmallVector
<std::string
, 3> Lines
;
105 // Parse the asm snippet and print it.
106 while (!Bytes
.empty()) {
109 if (!Disasm_
->getInstruction(MI
, MISize
, Bytes
, 0, nulls())) {
110 writeEscaped
<Tag
>(OS
, join(Lines
, Separator
));
111 writeEscaped
<Tag
>(OS
, Separator
);
112 writeEscaped
<Tag
>(OS
, "[error decoding asm snippet]");
115 SmallString
<128> InstPrinterStr
; // FIXME: magic number.
116 raw_svector_ostream
OSS(InstPrinterStr
);
117 InstPrinter_
->printInst(&MI
, 0, "", *SubtargetInfo_
, OSS
);
118 Bytes
= Bytes
.drop_front(MISize
);
119 Lines
.emplace_back(InstPrinterStr
.str().trim());
121 writeEscaped
<Tag
>(OS
, join(Lines
, Separator
));
124 // Prints a row representing an instruction, along with scheduling info and
125 // point coordinates (measurements).
126 void Analysis::printInstructionRowCsv(const size_t PointId
,
127 raw_ostream
&OS
) const {
128 const InstructionBenchmark
&Point
= Clustering_
.getPoints()[PointId
];
129 writeClusterId
<kEscapeCsv
>(OS
, Clustering_
.getClusterIdForPoint(PointId
));
131 writeSnippet
<EscapeTag
, kEscapeCsv
>(OS
, Point
.AssembledSnippet
, "; ");
133 writeEscaped
<kEscapeCsv
>(OS
, Point
.Key
.Config
);
135 assert(!Point
.Key
.Instructions
.empty());
136 const MCInst
&MCI
= Point
.keyInstruction();
137 unsigned SchedClassId
;
138 std::tie(SchedClassId
, std::ignore
) = ResolvedSchedClass::resolveSchedClassId(
139 *SubtargetInfo_
, *InstrInfo_
, MCI
);
140 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
141 const MCSchedClassDesc
*const SCDesc
=
142 SubtargetInfo_
->getSchedModel().getSchedClassDesc(SchedClassId
);
143 writeEscaped
<kEscapeCsv
>(OS
, SCDesc
->Name
);
147 for (const auto &Measurement
: Point
.Measurements
) {
149 writeMeasurementValue
<kEscapeCsv
>(OS
, Measurement
.PerInstructionValue
);
154 Analysis::Analysis(const Target
&Target
,
155 std::unique_ptr
<MCSubtargetInfo
> SubtargetInfo
,
156 std::unique_ptr
<MCInstrInfo
> InstrInfo
,
157 const InstructionBenchmarkClustering
&Clustering
,
158 double AnalysisInconsistencyEpsilon
,
159 bool AnalysisDisplayUnstableOpcodes
,
160 const std::string
&ForceCpuName
)
161 : Clustering_(Clustering
), SubtargetInfo_(std::move(SubtargetInfo
)),
162 InstrInfo_(std::move(InstrInfo
)),
163 AnalysisInconsistencyEpsilonSquared_(AnalysisInconsistencyEpsilon
*
164 AnalysisInconsistencyEpsilon
),
165 AnalysisDisplayUnstableOpcodes_(AnalysisDisplayUnstableOpcodes
) {
166 if (Clustering
.getPoints().empty())
169 const InstructionBenchmark
&FirstPoint
= Clustering
.getPoints().front();
170 const std::string CpuName
=
171 ForceCpuName
.empty() ? FirstPoint
.CpuName
: ForceCpuName
;
172 RegInfo_
.reset(Target
.createMCRegInfo(FirstPoint
.LLVMTriple
));
173 MCTargetOptions MCOptions
;
175 Target
.createMCAsmInfo(*RegInfo_
, FirstPoint
.LLVMTriple
, MCOptions
));
176 SubtargetInfo_
.reset(
177 Target
.createMCSubtargetInfo(FirstPoint
.LLVMTriple
, CpuName
, ""));
178 InstPrinter_
.reset(Target
.createMCInstPrinter(
179 Triple(FirstPoint
.LLVMTriple
), 0 /*default variant*/, *AsmInfo_
,
180 *InstrInfo_
, *RegInfo_
));
183 std::make_unique
<MCContext
>(Triple(FirstPoint
.LLVMTriple
), AsmInfo_
.get(),
184 RegInfo_
.get(), SubtargetInfo_
.get());
185 Disasm_
.reset(Target
.createMCDisassembler(*SubtargetInfo_
, *Context_
));
186 assert(Disasm_
&& "cannot create MCDisassembler. missing call to "
187 "InitializeXXXTargetDisassembler ?");
191 Error
Analysis::run
<Analysis::PrintClusters
>(raw_ostream
&OS
) const {
192 if (Clustering_
.getPoints().empty())
193 return Error::success();
196 OS
<< "cluster_id" << kCsvSep
<< "opcode_name" << kCsvSep
<< "config"
197 << kCsvSep
<< "sched_class";
198 for (const auto &Measurement
: Clustering_
.getPoints().front().Measurements
) {
200 writeEscaped
<kEscapeCsv
>(OS
, Measurement
.Key
);
205 for (const auto &ClusterIt
: Clustering_
.getValidClusters()) {
206 for (const size_t PointId
: ClusterIt
.PointIndices
) {
207 printInstructionRowCsv(PointId
, OS
);
211 return Error::success();
214 Analysis::ResolvedSchedClassAndPoints::ResolvedSchedClassAndPoints(
215 ResolvedSchedClass
&&RSC
)
216 : RSC(std::move(RSC
)) {}
218 std::vector
<Analysis::ResolvedSchedClassAndPoints
>
219 Analysis::makePointsPerSchedClass() const {
220 std::vector
<ResolvedSchedClassAndPoints
> Entries
;
221 // Maps SchedClassIds to index in result.
222 std::unordered_map
<unsigned, size_t> SchedClassIdToIndex
;
223 const auto &Points
= Clustering_
.getPoints();
224 for (size_t PointId
= 0, E
= Points
.size(); PointId
< E
; ++PointId
) {
225 const InstructionBenchmark
&Point
= Points
[PointId
];
226 if (!Point
.Error
.empty())
228 assert(!Point
.Key
.Instructions
.empty());
229 // FIXME: we should be using the tuple of classes for instructions in the
231 const MCInst
&MCI
= Point
.keyInstruction();
232 unsigned SchedClassId
;
234 std::tie(SchedClassId
, WasVariant
) =
235 ResolvedSchedClass::resolveSchedClassId(*SubtargetInfo_
, *InstrInfo_
,
237 const auto IndexIt
= SchedClassIdToIndex
.find(SchedClassId
);
238 if (IndexIt
== SchedClassIdToIndex
.end()) {
239 // Create a new entry.
240 SchedClassIdToIndex
.emplace(SchedClassId
, Entries
.size());
241 ResolvedSchedClassAndPoints
Entry(
242 ResolvedSchedClass(*SubtargetInfo_
, SchedClassId
, WasVariant
));
243 Entry
.PointIds
.push_back(PointId
);
244 Entries
.push_back(std::move(Entry
));
246 // Append to the existing entry.
247 Entries
[IndexIt
->second
].PointIds
.push_back(PointId
);
253 // Parallel benchmarks repeat the same opcode multiple times. Just show this
254 // opcode and show the whole snippet only on hover.
255 static void writeParallelSnippetHtml(raw_ostream
&OS
,
256 const std::vector
<MCInst
> &Instructions
,
257 const MCInstrInfo
&InstrInfo
) {
258 if (Instructions
.empty())
260 writeEscaped
<kEscapeHtml
>(OS
, InstrInfo
.getName(Instructions
[0].getOpcode()));
261 if (Instructions
.size() > 1)
262 OS
<< " (x" << Instructions
.size() << ")";
265 // Latency tries to find a serial path. Just show the opcode path and show the
266 // whole snippet only on hover.
267 static void writeLatencySnippetHtml(raw_ostream
&OS
,
268 const std::vector
<MCInst
> &Instructions
,
269 const MCInstrInfo
&InstrInfo
) {
271 for (const MCInst
&Instr
: Instructions
) {
276 writeEscaped
<kEscapeHtml
>(OS
, InstrInfo
.getName(Instr
.getOpcode()));
280 void Analysis::printPointHtml(const InstructionBenchmark
&Point
,
281 llvm::raw_ostream
&OS
) const {
282 OS
<< "<li><span class=\"mono\" title=\"";
283 writeSnippet
<EscapeTag
, kEscapeHtmlString
>(OS
, Point
.AssembledSnippet
, "\n");
285 switch (Point
.Mode
) {
286 case InstructionBenchmark::Latency
:
287 writeLatencySnippetHtml(OS
, Point
.Key
.Instructions
, *InstrInfo_
);
289 case InstructionBenchmark::Uops
:
290 case InstructionBenchmark::InverseThroughput
:
291 writeParallelSnippetHtml(OS
, Point
.Key
.Instructions
, *InstrInfo_
);
294 llvm_unreachable("invalid mode");
296 OS
<< "</span> <span class=\"mono\">";
297 writeEscaped
<kEscapeHtml
>(OS
, Point
.Key
.Config
);
298 OS
<< "</span></li>";
301 void Analysis::printSchedClassClustersHtml(
302 const std::vector
<SchedClassCluster
> &Clusters
,
303 const ResolvedSchedClass
&RSC
, raw_ostream
&OS
) const {
304 const auto &Points
= Clustering_
.getPoints();
305 OS
<< "<table class=\"sched-class-clusters\">";
306 OS
<< "<tr><th>ClusterId</th><th>Opcode/Config</th>";
307 assert(!Clusters
.empty());
308 for (const auto &Measurement
:
309 Points
[Clusters
[0].getPointIds()[0]].Measurements
) {
311 writeEscaped
<kEscapeHtml
>(OS
, Measurement
.Key
);
315 for (const SchedClassCluster
&Cluster
: Clusters
) {
317 << (Cluster
.measurementsMatch(*SubtargetInfo_
, RSC
, Clustering_
,
318 AnalysisInconsistencyEpsilonSquared_
)
322 writeClusterId
<kEscapeHtml
>(OS
, Cluster
.id());
323 OS
<< "</td><td><ul>";
324 for (const size_t PointId
: Cluster
.getPointIds()) {
325 printPointHtml(Points
[PointId
], OS
);
328 for (const auto &Stats
: Cluster
.getCentroid().getStats()) {
329 OS
<< "<td class=\"measurement\">";
330 writeMeasurementValue
<kEscapeHtml
>(OS
, Stats
.avg());
331 OS
<< "<br><span class=\"minmax\">[";
332 writeMeasurementValue
<kEscapeHtml
>(OS
, Stats
.min());
334 writeMeasurementValue
<kEscapeHtml
>(OS
, Stats
.max());
335 OS
<< "]</span></td>";
342 void Analysis::SchedClassCluster::addPoint(
343 size_t PointId
, const InstructionBenchmarkClustering
&Clustering
) {
344 PointIds
.push_back(PointId
);
345 const auto &Point
= Clustering
.getPoints()[PointId
];
346 if (ClusterId
.isUndef())
347 ClusterId
= Clustering
.getClusterIdForPoint(PointId
);
348 assert(ClusterId
== Clustering
.getClusterIdForPoint(PointId
));
350 Centroid
.addPoint(Point
.Measurements
);
353 bool Analysis::SchedClassCluster::measurementsMatch(
354 const MCSubtargetInfo
&STI
, const ResolvedSchedClass
&RSC
,
355 const InstructionBenchmarkClustering
&Clustering
,
356 const double AnalysisInconsistencyEpsilonSquared_
) const {
357 assert(!Clustering
.getPoints().empty());
358 const InstructionBenchmark::ModeE Mode
= Clustering
.getPoints()[0].Mode
;
360 if (!Centroid
.validate(Mode
))
363 const std::vector
<BenchmarkMeasure
> ClusterCenterPoint
=
364 Centroid
.getAsPoint();
366 const std::vector
<BenchmarkMeasure
> SchedClassPoint
=
367 RSC
.getAsPoint(Mode
, STI
, Centroid
.getStats());
368 if (SchedClassPoint
.empty())
369 return false; // In Uops mode validate() may not be enough.
371 assert(ClusterCenterPoint
.size() == SchedClassPoint
.size() &&
372 "Expected measured/sched data dimensions to match.");
374 return Clustering
.isNeighbour(ClusterCenterPoint
, SchedClassPoint
,
375 AnalysisInconsistencyEpsilonSquared_
);
378 void Analysis::printSchedClassDescHtml(const ResolvedSchedClass
&RSC
,
379 raw_ostream
&OS
) const {
380 OS
<< "<table class=\"sched-class-desc\">";
381 OS
<< "<tr><th>Valid</th><th>Variant</th><th>NumMicroOps</th><th>Latency</"
382 "th><th>RThroughput</th><th>WriteProcRes</th><th title=\"This is the "
383 "idealized unit resource (port) pressure assuming ideal "
384 "distribution\">Idealized Resource Pressure</th></tr>";
385 if (RSC
.SCDesc
->isValid()) {
386 const auto &SM
= SubtargetInfo_
->getSchedModel();
387 OS
<< "<tr><td>✔</td>";
388 OS
<< "<td>" << (RSC
.WasVariant
? "✔" : "✕") << "</td>";
389 OS
<< "<td>" << RSC
.SCDesc
->NumMicroOps
<< "</td>";
392 for (int I
= 0, E
= RSC
.SCDesc
->NumWriteLatencyEntries
; I
< E
; ++I
) {
393 const auto *const Entry
=
394 SubtargetInfo_
->getWriteLatencyEntry(RSC
.SCDesc
, I
);
395 OS
<< "<li>" << Entry
->Cycles
;
396 if (RSC
.SCDesc
->NumWriteLatencyEntries
> 1) {
397 // Dismabiguate if more than 1 latency.
398 OS
<< " (WriteResourceID " << Entry
->WriteResourceID
<< ")";
403 // inverse throughput.
405 writeMeasurementValue
<kEscapeHtml
>(
407 MCSchedModel::getReciprocalThroughput(*SubtargetInfo_
, *RSC
.SCDesc
));
411 for (const auto &WPR
: RSC
.NonRedundantWriteProcRes
) {
412 OS
<< "<li><span class=\"mono\">";
413 writeEscaped
<kEscapeHtml
>(OS
,
414 SM
.getProcResource(WPR
.ProcResourceIdx
)->Name
);
415 OS
<< "</span>: " << WPR
.Cycles
<< "</li>";
418 // Idealized port pressure.
420 for (const auto &Pressure
: RSC
.IdealizedProcResPressure
) {
421 OS
<< "<li><span class=\"mono\">";
422 writeEscaped
<kEscapeHtml
>(OS
, SubtargetInfo_
->getSchedModel()
423 .getProcResource(Pressure
.first
)
426 writeMeasurementValue
<kEscapeHtml
>(OS
, Pressure
.second
);
432 OS
<< "<tr><td>✕</td><td></td><td></td></tr>";
437 void Analysis::printClusterRawHtml(
438 const InstructionBenchmarkClustering::ClusterId
&Id
, StringRef display_name
,
439 llvm::raw_ostream
&OS
) const {
440 const auto &Points
= Clustering_
.getPoints();
441 const auto &Cluster
= Clustering_
.getCluster(Id
);
442 if (Cluster
.PointIndices
.empty())
445 OS
<< "<div class=\"inconsistency\"><p>" << display_name
<< " Cluster ("
446 << Cluster
.PointIndices
.size() << " points)</p>";
447 OS
<< "<table class=\"sched-class-clusters\">";
449 OS
<< "<tr><th>ClusterId</th><th>Opcode/Config</th>";
450 for (const auto &Measurement
: Points
[Cluster
.PointIndices
[0]].Measurements
) {
452 writeEscaped
<kEscapeHtml
>(OS
, Measurement
.Key
);
458 for (const auto &PointId
: Cluster
.PointIndices
) {
459 OS
<< "<tr class=\"bad-cluster\"><td>" << display_name
<< "</td><td><ul>";
460 printPointHtml(Points
[PointId
], OS
);
462 for (const auto &Measurement
: Points
[PointId
].Measurements
) {
463 OS
<< "<td class=\"measurement\">";
464 writeMeasurementValue
<kEscapeHtml
>(OS
, Measurement
.PerInstructionValue
);
472 } // namespace exegesis
474 static constexpr const char kHtmlHead
[] = R
"(
476 <title>llvm-exegesis Analysis Results</title>
479 font-family: sans-serif
481 span.sched-class-name {
483 font-family: monospace;
486 font-family: monospace;
489 font-family: monospace;
496 border-collapse: collapse;
498 table, table tr,td,th {
499 border: 1px solid #444;
504 list-style-type: none;
506 table.sched-class-clusters td {
510 padding-bottom: 10px;
512 table.sched-class-desc td {
519 font-family: monospace;
524 tr.good-cluster td.measurement {
527 tr.bad-cluster td.measurement {
530 tr.good-cluster td.measurement span.minmax {
533 tr.bad-cluster td.measurement span.minmax {
541 Error
Analysis::run
<Analysis::PrintSchedClassInconsistencies
>(
542 raw_ostream
&OS
) const {
543 const auto &FirstPoint
= Clustering_
.getPoints()[0];
545 OS
<< "<!DOCTYPE html><html>" << kHtmlHead
<< "<body>";
546 OS
<< "<h1><span class=\"mono\">llvm-exegesis</span> Analysis Results</h1>";
547 OS
<< "<h3>Triple: <span class=\"mono\">";
548 writeEscaped
<kEscapeHtml
>(OS
, FirstPoint
.LLVMTriple
);
549 OS
<< "</span></h3><h3>Cpu: <span class=\"mono\">";
550 writeEscaped
<kEscapeHtml
>(OS
, FirstPoint
.CpuName
);
551 OS
<< "</span></h3>";
553 for (const auto &RSCAndPoints
: makePointsPerSchedClass()) {
554 if (!RSCAndPoints
.RSC
.SCDesc
)
556 // Bucket sched class points into sched class clusters.
557 std::vector
<SchedClassCluster
> SchedClassClusters
;
558 for (const size_t PointId
: RSCAndPoints
.PointIds
) {
559 const auto &ClusterId
= Clustering_
.getClusterIdForPoint(PointId
);
560 if (!ClusterId
.isValid())
561 continue; // Ignore noise and errors. FIXME: take noise into account ?
562 if (ClusterId
.isUnstable() ^ AnalysisDisplayUnstableOpcodes_
)
563 continue; // Either display stable or unstable clusters only.
564 auto SchedClassClusterIt
= llvm::find_if(
565 SchedClassClusters
, [ClusterId
](const SchedClassCluster
&C
) {
566 return C
.id() == ClusterId
;
568 if (SchedClassClusterIt
== SchedClassClusters
.end()) {
569 SchedClassClusters
.emplace_back();
570 SchedClassClusterIt
= std::prev(SchedClassClusters
.end());
572 SchedClassClusterIt
->addPoint(PointId
, Clustering_
);
575 // Print any scheduling class that has at least one cluster that does not
576 // match the checked-in data.
577 if (all_of(SchedClassClusters
, [this,
578 &RSCAndPoints
](const SchedClassCluster
&C
) {
579 return C
.measurementsMatch(*SubtargetInfo_
, RSCAndPoints
.RSC
,
581 AnalysisInconsistencyEpsilonSquared_
);
583 continue; // Nothing weird.
585 OS
<< "<div class=\"inconsistency\"><p>Sched Class <span "
586 "class=\"sched-class-name\">";
587 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
588 writeEscaped
<kEscapeHtml
>(OS
, RSCAndPoints
.RSC
.SCDesc
->Name
);
590 OS
<< RSCAndPoints
.RSC
.SchedClassId
;
592 OS
<< "</span> contains instructions whose performance characteristics do"
593 " not match that of LLVM:</p>";
594 printSchedClassClustersHtml(SchedClassClusters
, RSCAndPoints
.RSC
, OS
);
595 OS
<< "<p>llvm SchedModel data:</p>";
596 printSchedClassDescHtml(RSCAndPoints
.RSC
, OS
);
600 printClusterRawHtml(InstructionBenchmarkClustering::ClusterId::noise(),
603 OS
<< "</body></html>";
604 return Error::success();
607 } // namespace exegesis