xref: /llvm-project/llvm/tools/llvm-exegesis/lib/Analysis.cpp (revision 1a0d595f15602b6fe222f0ee7dfd0285e433ab7c)
1 //===-- Analysis.cpp --------------------------------------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Analysis.h"
10 #include "BenchmarkResult.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/Support/FormatVariadic.h"
14 #include <limits>
15 #include <unordered_set>
16 #include <vector>
17 
18 namespace llvm {
19 namespace exegesis {
20 
21 static const char kCsvSep = ',';
22 
23 static unsigned resolveSchedClassId(const llvm::MCSubtargetInfo &STI,
24                                     unsigned SchedClassId,
25                                     const llvm::MCInst &MCI) {
26   const auto &SM = STI.getSchedModel();
27   while (SchedClassId && SM.getSchedClassDesc(SchedClassId)->isVariant())
28     SchedClassId =
29         STI.resolveVariantSchedClass(SchedClassId, &MCI, SM.getProcessorID());
30   return SchedClassId;
31 }
32 
33 namespace {
34 
35 enum EscapeTag { kEscapeCsv, kEscapeHtml, kEscapeHtmlString };
36 
37 template <EscapeTag Tag>
38 void writeEscaped(llvm::raw_ostream &OS, const llvm::StringRef S);
39 
40 template <>
41 void writeEscaped<kEscapeCsv>(llvm::raw_ostream &OS, const llvm::StringRef S) {
42   if (std::find(S.begin(), S.end(), kCsvSep) == S.end()) {
43     OS << S;
44   } else {
45     // Needs escaping.
46     OS << '"';
47     for (const char C : S) {
48       if (C == '"')
49         OS << "\"\"";
50       else
51         OS << C;
52     }
53     OS << '"';
54   }
55 }
56 
57 template <>
58 void writeEscaped<kEscapeHtml>(llvm::raw_ostream &OS, const llvm::StringRef S) {
59   for (const char C : S) {
60     if (C == '<')
61       OS << "&lt;";
62     else if (C == '>')
63       OS << "&gt;";
64     else if (C == '&')
65       OS << "&amp;";
66     else
67       OS << C;
68   }
69 }
70 
71 template <>
72 void writeEscaped<kEscapeHtmlString>(llvm::raw_ostream &OS,
73                                      const llvm::StringRef S) {
74   for (const char C : S) {
75     if (C == '"')
76       OS << "\\\"";
77     else
78       OS << C;
79   }
80 }
81 
82 } // namespace
83 
84 template <EscapeTag Tag>
85 static void
86 writeClusterId(llvm::raw_ostream &OS,
87                const InstructionBenchmarkClustering::ClusterId &CID) {
88   if (CID.isNoise())
89     writeEscaped<Tag>(OS, "[noise]");
90   else if (CID.isError())
91     writeEscaped<Tag>(OS, "[error]");
92   else
93     OS << CID.getId();
94 }
95 
96 template <EscapeTag Tag>
97 static void writeMeasurementValue(llvm::raw_ostream &OS, const double Value) {
98   // Given Value, if we wanted to serialize it to a string,
99   // how many base-10 digits will we need to store, max?
100   static constexpr auto MaxDigitCount =
101       std::numeric_limits<decltype(Value)>::max_digits10;
102   // Also, we will need a decimal separator.
103   static constexpr auto DecimalSeparatorLen = 1; // '.' e.g.
104   // So how long of a string will the serialization produce, max?
105   static constexpr auto SerializationLen = MaxDigitCount + DecimalSeparatorLen;
106 
107   // WARNING: when changing the format, also adjust the small-size estimate ^.
108   static constexpr StringLiteral SimpleFloatFormat = StringLiteral("{0:F}");
109 
110   writeEscaped<Tag>(
111       OS,
112       llvm::formatv(SimpleFloatFormat.data(), Value).sstr<SerializationLen>());
113 }
114 
115 template <typename EscapeTag, EscapeTag Tag>
116 void Analysis::writeSnippet(llvm::raw_ostream &OS,
117                             llvm::ArrayRef<uint8_t> Bytes,
118                             const char *Separator) const {
119   llvm::SmallVector<std::string, 3> Lines;
120   // Parse the asm snippet and print it.
121   while (!Bytes.empty()) {
122     llvm::MCInst MI;
123     uint64_t MISize = 0;
124     if (!Disasm_->getInstruction(MI, MISize, Bytes, 0, llvm::nulls(),
125                                  llvm::nulls())) {
126       writeEscaped<Tag>(OS, llvm::join(Lines, Separator));
127       writeEscaped<Tag>(OS, Separator);
128       writeEscaped<Tag>(OS, "[error decoding asm snippet]");
129       return;
130     }
131     llvm::SmallString<128> InstPrinterStr; // FIXME: magic number.
132     llvm::raw_svector_ostream OSS(InstPrinterStr);
133     InstPrinter_->printInst(&MI, OSS, "", *SubtargetInfo_);
134     Bytes = Bytes.drop_front(MISize);
135     Lines.emplace_back(llvm::StringRef(InstPrinterStr).trim());
136   }
137   writeEscaped<Tag>(OS, llvm::join(Lines, Separator));
138 }
139 
140 // Prints a row representing an instruction, along with scheduling info and
141 // point coordinates (measurements).
142 void Analysis::printInstructionRowCsv(const size_t PointId,
143                                       llvm::raw_ostream &OS) const {
144   const InstructionBenchmark &Point = Clustering_.getPoints()[PointId];
145   writeClusterId<kEscapeCsv>(OS, Clustering_.getClusterIdForPoint(PointId));
146   OS << kCsvSep;
147   writeSnippet<EscapeTag, kEscapeCsv>(OS, Point.AssembledSnippet, "; ");
148   OS << kCsvSep;
149   writeEscaped<kEscapeCsv>(OS, Point.Key.Config);
150   OS << kCsvSep;
151   assert(!Point.Key.Instructions.empty());
152   const llvm::MCInst &MCI = Point.Key.Instructions[0];
153   const unsigned SchedClassId = resolveSchedClassId(
154       *SubtargetInfo_, InstrInfo_->get(MCI.getOpcode()).getSchedClass(), MCI);
155 
156 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
157   const llvm::MCSchedClassDesc *const SCDesc =
158       SubtargetInfo_->getSchedModel().getSchedClassDesc(SchedClassId);
159   writeEscaped<kEscapeCsv>(OS, SCDesc->Name);
160 #else
161   OS << SchedClassId;
162 #endif
163   for (const auto &Measurement : Point.Measurements) {
164     OS << kCsvSep;
165     writeMeasurementValue<kEscapeCsv>(OS, Measurement.PerInstructionValue);
166   }
167   OS << "\n";
168 }
169 
170 Analysis::Analysis(const llvm::Target &Target,
171                    const InstructionBenchmarkClustering &Clustering)
172     : Clustering_(Clustering) {
173   if (Clustering.getPoints().empty())
174     return;
175 
176   const InstructionBenchmark &FirstPoint = Clustering.getPoints().front();
177   InstrInfo_.reset(Target.createMCInstrInfo());
178   RegInfo_.reset(Target.createMCRegInfo(FirstPoint.LLVMTriple));
179   AsmInfo_.reset(Target.createMCAsmInfo(*RegInfo_, FirstPoint.LLVMTriple));
180   SubtargetInfo_.reset(Target.createMCSubtargetInfo(FirstPoint.LLVMTriple,
181                                                     FirstPoint.CpuName, ""));
182   InstPrinter_.reset(Target.createMCInstPrinter(
183       llvm::Triple(FirstPoint.LLVMTriple), 0 /*default variant*/, *AsmInfo_,
184       *InstrInfo_, *RegInfo_));
185 
186   Context_ = llvm::make_unique<llvm::MCContext>(AsmInfo_.get(), RegInfo_.get(),
187                                                 &ObjectFileInfo_);
188   Disasm_.reset(Target.createMCDisassembler(*SubtargetInfo_, *Context_));
189   assert(Disasm_ && "cannot create MCDisassembler. missing call to "
190                     "InitializeXXXTargetDisassembler ?");
191 }
192 
193 template <>
194 llvm::Error
195 Analysis::run<Analysis::PrintClusters>(llvm::raw_ostream &OS) const {
196   if (Clustering_.getPoints().empty())
197     return llvm::Error::success();
198 
199   // Write the header.
200   OS << "cluster_id" << kCsvSep << "opcode_name" << kCsvSep << "config"
201      << kCsvSep << "sched_class";
202   for (const auto &Measurement : Clustering_.getPoints().front().Measurements) {
203     OS << kCsvSep;
204     writeEscaped<kEscapeCsv>(OS, Measurement.Key);
205   }
206   OS << "\n";
207 
208   // Write the points.
209   const auto &Clusters = Clustering_.getValidClusters();
210   for (size_t I = 0, E = Clusters.size(); I < E; ++I) {
211     for (const size_t PointId : Clusters[I].PointIndices) {
212       printInstructionRowCsv(PointId, OS);
213     }
214     OS << "\n\n";
215   }
216   return llvm::Error::success();
217 }
218 
219 Analysis::ResolvedSchedClassAndPoints::ResolvedSchedClassAndPoints(
220     ResolvedSchedClass &&RSC)
221     : RSC(std::move(RSC)) {}
222 
223 std::vector<Analysis::ResolvedSchedClassAndPoints>
224 Analysis::makePointsPerSchedClass() const {
225   std::vector<ResolvedSchedClassAndPoints> Entries;
226   // Maps SchedClassIds to index in result.
227   std::unordered_map<unsigned, size_t> SchedClassIdToIndex;
228   const auto &Points = Clustering_.getPoints();
229   for (size_t PointId = 0, E = Points.size(); PointId < E; ++PointId) {
230     const InstructionBenchmark &Point = Points[PointId];
231     if (!Point.Error.empty())
232       continue;
233     assert(!Point.Key.Instructions.empty());
234     // FIXME: we should be using the tuple of classes for instructions in the
235     // snippet as key.
236     const llvm::MCInst &MCI = Point.Key.Instructions[0];
237     unsigned SchedClassId = InstrInfo_->get(MCI.getOpcode()).getSchedClass();
238     const bool WasVariant = SchedClassId && SubtargetInfo_->getSchedModel()
239                                                 .getSchedClassDesc(SchedClassId)
240                                                 ->isVariant();
241     SchedClassId = resolveSchedClassId(*SubtargetInfo_, SchedClassId, MCI);
242     const auto IndexIt = SchedClassIdToIndex.find(SchedClassId);
243     if (IndexIt == SchedClassIdToIndex.end()) {
244       // Create a new entry.
245       SchedClassIdToIndex.emplace(SchedClassId, Entries.size());
246       ResolvedSchedClassAndPoints Entry(
247           ResolvedSchedClass(*SubtargetInfo_, SchedClassId, WasVariant));
248       Entry.PointIds.push_back(PointId);
249       Entries.push_back(std::move(Entry));
250     } else {
251       // Append to the existing entry.
252       Entries[IndexIt->second].PointIds.push_back(PointId);
253     }
254   }
255   return Entries;
256 }
257 
258 // Uops repeat the same opcode over again. Just show this opcode and show the
259 // whole snippet only on hover.
260 static void writeUopsSnippetHtml(llvm::raw_ostream &OS,
261                                  const std::vector<llvm::MCInst> &Instructions,
262                                  const llvm::MCInstrInfo &InstrInfo) {
263   if (Instructions.empty())
264     return;
265   writeEscaped<kEscapeHtml>(OS, InstrInfo.getName(Instructions[0].getOpcode()));
266   if (Instructions.size() > 1)
267     OS << " (x" << Instructions.size() << ")";
268 }
269 
270 // Latency tries to find a serial path. Just show the opcode path and show the
271 // whole snippet only on hover.
272 static void
273 writeLatencySnippetHtml(llvm::raw_ostream &OS,
274                         const std::vector<llvm::MCInst> &Instructions,
275                         const llvm::MCInstrInfo &InstrInfo) {
276   bool First = true;
277   for (const llvm::MCInst &Instr : Instructions) {
278     if (First)
279       First = false;
280     else
281       OS << " &rarr; ";
282     writeEscaped<kEscapeHtml>(OS, InstrInfo.getName(Instr.getOpcode()));
283   }
284 }
285 
286 void Analysis::printSchedClassClustersHtml(
287     const std::vector<SchedClassCluster> &Clusters,
288     const ResolvedSchedClass &RSC, llvm::raw_ostream &OS) const {
289   const auto &Points = Clustering_.getPoints();
290   OS << "<table class=\"sched-class-clusters\">";
291   OS << "<tr><th>ClusterId</th><th>Opcode/Config</th>";
292   assert(!Clusters.empty());
293   for (const auto &Measurement :
294        Points[Clusters[0].getPointIds()[0]].Measurements) {
295     OS << "<th>";
296     writeEscaped<kEscapeHtml>(OS, Measurement.Key);
297     OS << "</th>";
298   }
299   OS << "</tr>";
300   for (const SchedClassCluster &Cluster : Clusters) {
301     OS << "<tr class=\""
302        << (Cluster.measurementsMatch(*SubtargetInfo_, RSC, Clustering_)
303                ? "good-cluster"
304                : "bad-cluster")
305        << "\"><td>";
306     writeClusterId<kEscapeHtml>(OS, Cluster.id());
307     OS << "</td><td><ul>";
308     for (const size_t PointId : Cluster.getPointIds()) {
309       const auto &Point = Points[PointId];
310       OS << "<li><span class=\"mono\" title=\"";
311       writeSnippet<EscapeTag, kEscapeHtmlString>(OS, Point.AssembledSnippet,
312                                                  "\n");
313       OS << "\">";
314       switch (Point.Mode) {
315       case InstructionBenchmark::Latency:
316         writeLatencySnippetHtml(OS, Point.Key.Instructions, *InstrInfo_);
317         break;
318       case InstructionBenchmark::Uops:
319       case InstructionBenchmark::InverseThroughput:
320         writeUopsSnippetHtml(OS, Point.Key.Instructions, *InstrInfo_);
321         break;
322       default:
323         llvm_unreachable("invalid mode");
324       }
325       OS << "</span> <span class=\"mono\">";
326       writeEscaped<kEscapeHtml>(OS, Point.Key.Config);
327       OS << "</span></li>";
328     }
329     OS << "</ul></td>";
330     for (const auto &Stats : Cluster.getRepresentative()) {
331       OS << "<td class=\"measurement\">";
332       writeMeasurementValue<kEscapeHtml>(OS, Stats.avg());
333       OS << "<br><span class=\"minmax\">[";
334       writeMeasurementValue<kEscapeHtml>(OS, Stats.min());
335       OS << ";";
336       writeMeasurementValue<kEscapeHtml>(OS, Stats.max());
337       OS << "]</span></td>";
338     }
339     OS << "</tr>";
340   }
341   OS << "</table>";
342 }
343 
344 // Return the non-redundant list of WriteProcRes used by the given sched class.
345 // The scheduling model for LLVM is such that each instruction has a certain
346 // number of uops which consume resources which are described by WriteProcRes
347 // entries. Each entry describe how many cycles are spent on a specific ProcRes
348 // kind.
349 // For example, an instruction might have 3 uOps, one dispatching on P0
350 // (ProcResIdx=1) and two on P06 (ProcResIdx = 7).
351 // Note that LLVM additionally denormalizes resource consumption to include
352 // usage of super resources by subresources. So in practice if there exists a
353 // P016 (ProcResIdx=10), then the cycles consumed by P0 are also consumed by
354 // P06 (ProcResIdx = 7) and P016 (ProcResIdx = 10), and the resources consumed
355 // by P06 are also consumed by P016. In the figure below, parenthesized cycles
356 // denote implied usage of superresources by subresources:
357 //            P0      P06    P016
358 //     uOp1    1      (1)     (1)
359 //     uOp2            1      (1)
360 //     uOp3            1      (1)
361 //     =============================
362 //             1       3       3
363 // Eventually we end up with three entries for the WriteProcRes of the
364 // instruction:
365 //    {ProcResIdx=1,  Cycles=1}  // P0
366 //    {ProcResIdx=7,  Cycles=3}  // P06
367 //    {ProcResIdx=10, Cycles=3}  // P016
368 //
369 // Note that in this case, P016 does not contribute any cycles, so it would
370 // be removed by this function.
371 // FIXME: Move this to MCSubtargetInfo and use it in llvm-mca.
372 static llvm::SmallVector<llvm::MCWriteProcResEntry, 8>
373 getNonRedundantWriteProcRes(const llvm::MCSchedClassDesc &SCDesc,
374                             const llvm::MCSubtargetInfo &STI) {
375   llvm::SmallVector<llvm::MCWriteProcResEntry, 8> Result;
376   const auto &SM = STI.getSchedModel();
377   const unsigned NumProcRes = SM.getNumProcResourceKinds();
378 
379   // This assumes that the ProcResDescs are sorted in topological order, which
380   // is guaranteed by the tablegen backend.
381   llvm::SmallVector<float, 32> ProcResUnitUsage(NumProcRes);
382   for (const auto *WPR = STI.getWriteProcResBegin(&SCDesc),
383                   *const WPREnd = STI.getWriteProcResEnd(&SCDesc);
384        WPR != WPREnd; ++WPR) {
385     const llvm::MCProcResourceDesc *const ProcResDesc =
386         SM.getProcResource(WPR->ProcResourceIdx);
387     if (ProcResDesc->SubUnitsIdxBegin == nullptr) {
388       // This is a ProcResUnit.
389       Result.push_back({WPR->ProcResourceIdx, WPR->Cycles});
390       ProcResUnitUsage[WPR->ProcResourceIdx] += WPR->Cycles;
391     } else {
392       // This is a ProcResGroup. First see if it contributes any cycles or if
393       // it has cycles just from subunits.
394       float RemainingCycles = WPR->Cycles;
395       for (const auto *SubResIdx = ProcResDesc->SubUnitsIdxBegin;
396            SubResIdx != ProcResDesc->SubUnitsIdxBegin + ProcResDesc->NumUnits;
397            ++SubResIdx) {
398         RemainingCycles -= ProcResUnitUsage[*SubResIdx];
399       }
400       if (RemainingCycles < 0.01f) {
401         // The ProcResGroup contributes no cycles of its own.
402         continue;
403       }
404       // The ProcResGroup contributes `RemainingCycles` cycles of its own.
405       Result.push_back({WPR->ProcResourceIdx,
406                         static_cast<uint16_t>(std::round(RemainingCycles))});
407       // Spread the remaining cycles over all subunits.
408       for (const auto *SubResIdx = ProcResDesc->SubUnitsIdxBegin;
409            SubResIdx != ProcResDesc->SubUnitsIdxBegin + ProcResDesc->NumUnits;
410            ++SubResIdx) {
411         ProcResUnitUsage[*SubResIdx] += RemainingCycles / ProcResDesc->NumUnits;
412       }
413     }
414   }
415   return Result;
416 }
417 
418 Analysis::ResolvedSchedClass::ResolvedSchedClass(
419     const llvm::MCSubtargetInfo &STI, unsigned ResolvedSchedClassId,
420     bool WasVariant)
421     : SchedClassId(ResolvedSchedClassId), SCDesc(STI.getSchedModel().getSchedClassDesc(ResolvedSchedClassId)),
422       WasVariant(WasVariant),
423       NonRedundantWriteProcRes(getNonRedundantWriteProcRes(*SCDesc, STI)),
424       IdealizedProcResPressure(computeIdealizedProcResPressure(
425           STI.getSchedModel(), NonRedundantWriteProcRes)) {
426   assert((SCDesc == nullptr || !SCDesc->isVariant()) &&
427          "ResolvedSchedClass should never be variant");
428 }
429 
430 void Analysis::SchedClassCluster::addPoint(
431     size_t PointId, const InstructionBenchmarkClustering &Clustering) {
432   PointIds.push_back(PointId);
433   const auto &Point = Clustering.getPoints()[PointId];
434   if (ClusterId.isUndef()) {
435     ClusterId = Clustering.getClusterIdForPoint(PointId);
436     Representative.resize(Point.Measurements.size());
437   }
438   for (size_t I = 0, E = Point.Measurements.size(); I < E; ++I) {
439     Representative[I].push(Point.Measurements[I]);
440   }
441   assert(ClusterId == Clustering.getClusterIdForPoint(PointId));
442 }
443 
444 // Returns a ProxResIdx by id or name.
445 static unsigned findProcResIdx(const llvm::MCSubtargetInfo &STI,
446                                const llvm::StringRef NameOrId) {
447   // Interpret the key as an ProcResIdx.
448   unsigned ProcResIdx = 0;
449   if (llvm::to_integer(NameOrId, ProcResIdx, 10))
450     return ProcResIdx;
451   // Interpret the key as a ProcRes name.
452   const auto &SchedModel = STI.getSchedModel();
453   for (int I = 0, E = SchedModel.getNumProcResourceKinds(); I < E; ++I) {
454     if (NameOrId == SchedModel.getProcResource(I)->Name)
455       return I;
456   }
457   return 0;
458 }
459 
460 bool Analysis::SchedClassCluster::measurementsMatch(
461     const llvm::MCSubtargetInfo &STI, const ResolvedSchedClass &RSC,
462     const InstructionBenchmarkClustering &Clustering) const {
463   const size_t NumMeasurements = Representative.size();
464   std::vector<BenchmarkMeasure> ClusterCenterPoint(NumMeasurements);
465   std::vector<BenchmarkMeasure> SchedClassPoint(NumMeasurements);
466   // Latency case.
467   assert(!Clustering.getPoints().empty());
468   const InstructionBenchmark::ModeE Mode = Clustering.getPoints()[0].Mode;
469   if (Mode == InstructionBenchmark::Latency) {
470     if (NumMeasurements != 1) {
471       llvm::errs()
472           << "invalid number of measurements in latency mode: expected 1, got "
473           << NumMeasurements << "\n";
474       return false;
475     }
476     // Find the latency.
477     SchedClassPoint[0].PerInstructionValue = 0.0;
478     for (unsigned I = 0; I < RSC.SCDesc->NumWriteLatencyEntries; ++I) {
479       const llvm::MCWriteLatencyEntry *const WLE =
480           STI.getWriteLatencyEntry(RSC.SCDesc, I);
481       SchedClassPoint[0].PerInstructionValue =
482           std::max<double>(SchedClassPoint[0].PerInstructionValue, WLE->Cycles);
483     }
484     ClusterCenterPoint[0].PerInstructionValue = Representative[0].avg();
485   } else if (Mode == InstructionBenchmark::Uops) {
486     for (int I = 0, E = Representative.size(); I < E; ++I) {
487       const auto Key = Representative[I].key();
488       uint16_t ProcResIdx = findProcResIdx(STI, Key);
489       if (ProcResIdx > 0) {
490         // Find the pressure on ProcResIdx `Key`.
491         const auto ProcResPressureIt =
492             std::find_if(RSC.IdealizedProcResPressure.begin(),
493                          RSC.IdealizedProcResPressure.end(),
494                          [ProcResIdx](const std::pair<uint16_t, float> &WPR) {
495                            return WPR.first == ProcResIdx;
496                          });
497         SchedClassPoint[I].PerInstructionValue =
498             ProcResPressureIt == RSC.IdealizedProcResPressure.end()
499                 ? 0.0
500                 : ProcResPressureIt->second;
501       } else if (Key == "NumMicroOps") {
502         SchedClassPoint[I].PerInstructionValue = RSC.SCDesc->NumMicroOps;
503       } else {
504         llvm::errs() << "expected `key` to be either a ProcResIdx or a ProcRes "
505                         "name, got "
506                      << Key << "\n";
507         return false;
508       }
509       ClusterCenterPoint[I].PerInstructionValue = Representative[I].avg();
510     }
511   } else if (Mode == InstructionBenchmark::InverseThroughput) {
512     for (int I = 0, E = Representative.size(); I < E; ++I) {
513       SchedClassPoint[I].PerInstructionValue =
514           MCSchedModel::getReciprocalThroughput(STI, *RSC.SCDesc);
515       ClusterCenterPoint[I].PerInstructionValue = Representative[I].min();
516     }
517   } else {
518     llvm_unreachable("unimplemented measurement matching mode");
519     return false;
520   }
521   return Clustering.isNeighbour(ClusterCenterPoint, SchedClassPoint);
522 }
523 
524 void Analysis::printSchedClassDescHtml(const ResolvedSchedClass &RSC,
525                                        llvm::raw_ostream &OS) const {
526   OS << "<table class=\"sched-class-desc\">";
527   OS << "<tr><th>Valid</th><th>Variant</th><th>NumMicroOps</th><th>Latency</"
528         "th><th>RThroughput</th><th>WriteProcRes</th><th title=\"This is the "
529         "idealized unit resource (port) pressure assuming ideal "
530         "distribution\">Idealized Resource Pressure</th></tr>";
531   if (RSC.SCDesc->isValid()) {
532     const auto &SM = SubtargetInfo_->getSchedModel();
533     OS << "<tr><td>&#10004;</td>";
534     OS << "<td>" << (RSC.WasVariant ? "&#10004;" : "&#10005;") << "</td>";
535     OS << "<td>" << RSC.SCDesc->NumMicroOps << "</td>";
536     // Latencies.
537     OS << "<td><ul>";
538     for (int I = 0, E = RSC.SCDesc->NumWriteLatencyEntries; I < E; ++I) {
539       const auto *const Entry =
540           SubtargetInfo_->getWriteLatencyEntry(RSC.SCDesc, I);
541       OS << "<li>" << Entry->Cycles;
542       if (RSC.SCDesc->NumWriteLatencyEntries > 1) {
543         // Dismabiguate if more than 1 latency.
544         OS << " (WriteResourceID " << Entry->WriteResourceID << ")";
545       }
546       OS << "</li>";
547     }
548     OS << "</ul></td>";
549     // inverse throughput.
550     OS << "<td>";
551     writeMeasurementValue<kEscapeHtml>(
552         OS,
553         MCSchedModel::getReciprocalThroughput(*SubtargetInfo_, *RSC.SCDesc));
554     OS << "</td>";
555     // WriteProcRes.
556     OS << "<td><ul>";
557     for (const auto &WPR : RSC.NonRedundantWriteProcRes) {
558       OS << "<li><span class=\"mono\">";
559       writeEscaped<kEscapeHtml>(OS,
560                                 SM.getProcResource(WPR.ProcResourceIdx)->Name);
561       OS << "</span>: " << WPR.Cycles << "</li>";
562     }
563     OS << "</ul></td>";
564     // Idealized port pressure.
565     OS << "<td><ul>";
566     for (const auto &Pressure : RSC.IdealizedProcResPressure) {
567       OS << "<li><span class=\"mono\">";
568       writeEscaped<kEscapeHtml>(OS, SubtargetInfo_->getSchedModel()
569                                         .getProcResource(Pressure.first)
570                                         ->Name);
571       OS << "</span>: ";
572       writeMeasurementValue<kEscapeHtml>(OS, Pressure.second);
573       OS << "</li>";
574     }
575     OS << "</ul></td>";
576     OS << "</tr>";
577   } else {
578     OS << "<tr><td>&#10005;</td><td></td><td></td></tr>";
579   }
580   OS << "</table>";
581 }
582 
583 static constexpr const char kHtmlHead[] = R"(
584 <head>
585 <title>llvm-exegesis Analysis Results</title>
586 <style>
587 body {
588   font-family: sans-serif
589 }
590 span.sched-class-name {
591   font-weight: bold;
592   font-family: monospace;
593 }
594 span.opcode {
595   font-family: monospace;
596 }
597 span.config {
598   font-family: monospace;
599 }
600 div.inconsistency {
601   margin-top: 50px;
602 }
603 table {
604   margin-left: 50px;
605   border-collapse: collapse;
606 }
607 table, table tr,td,th {
608   border: 1px solid #444;
609 }
610 table ul {
611   padding-left: 0px;
612   margin: 0px;
613   list-style-type: none;
614 }
615 table.sched-class-clusters td {
616   padding-left: 10px;
617   padding-right: 10px;
618   padding-top: 10px;
619   padding-bottom: 10px;
620 }
621 table.sched-class-desc td {
622   padding-left: 10px;
623   padding-right: 10px;
624   padding-top: 2px;
625   padding-bottom: 2px;
626 }
627 span.mono {
628   font-family: monospace;
629 }
630 td.measurement {
631   text-align: center;
632 }
633 tr.good-cluster td.measurement {
634   color: #292
635 }
636 tr.bad-cluster td.measurement {
637   color: #922
638 }
639 tr.good-cluster td.measurement span.minmax {
640   color: #888;
641 }
642 tr.bad-cluster td.measurement span.minmax {
643   color: #888;
644 }
645 </style>
646 </head>
647 )";
648 
649 template <>
650 llvm::Error Analysis::run<Analysis::PrintSchedClassInconsistencies>(
651     llvm::raw_ostream &OS) const {
652   const auto &FirstPoint = Clustering_.getPoints()[0];
653   // Print the header.
654   OS << "<!DOCTYPE html><html>" << kHtmlHead << "<body>";
655   OS << "<h1><span class=\"mono\">llvm-exegesis</span> Analysis Results</h1>";
656   OS << "<h3>Triple: <span class=\"mono\">";
657   writeEscaped<kEscapeHtml>(OS, FirstPoint.LLVMTriple);
658   OS << "</span></h3><h3>Cpu: <span class=\"mono\">";
659   writeEscaped<kEscapeHtml>(OS, FirstPoint.CpuName);
660   OS << "</span></h3>";
661 
662   for (const auto &RSCAndPoints : makePointsPerSchedClass()) {
663     if (!RSCAndPoints.RSC.SCDesc)
664       continue;
665     // Bucket sched class points into sched class clusters.
666     std::vector<SchedClassCluster> SchedClassClusters;
667     for (const size_t PointId : RSCAndPoints.PointIds) {
668       const auto &ClusterId = Clustering_.getClusterIdForPoint(PointId);
669       if (!ClusterId.isValid())
670         continue; // Ignore noise and errors. FIXME: take noise into account ?
671       auto SchedClassClusterIt =
672           std::find_if(SchedClassClusters.begin(), SchedClassClusters.end(),
673                        [ClusterId](const SchedClassCluster &C) {
674                          return C.id() == ClusterId;
675                        });
676       if (SchedClassClusterIt == SchedClassClusters.end()) {
677         SchedClassClusters.emplace_back();
678         SchedClassClusterIt = std::prev(SchedClassClusters.end());
679       }
680       SchedClassClusterIt->addPoint(PointId, Clustering_);
681     }
682 
683     // Print any scheduling class that has at least one cluster that does not
684     // match the checked-in data.
685     if (llvm::all_of(SchedClassClusters,
686                      [this, &RSCAndPoints](const SchedClassCluster &C) {
687                        return C.measurementsMatch(
688                            *SubtargetInfo_, RSCAndPoints.RSC, Clustering_);
689                      }))
690       continue; // Nothing weird.
691 
692     OS << "<div class=\"inconsistency\"><p>Sched Class <span "
693           "class=\"sched-class-name\">";
694 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
695     writeEscaped<kEscapeHtml>(OS, RSCAndPoints.RSC.SCDesc->Name);
696 #else
697     OS << RSCAndPoints.RSC.SchedClassId;
698 #endif
699     OS << "</span> contains instructions whose performance characteristics do"
700           " not match that of LLVM:</p>";
701     printSchedClassClustersHtml(SchedClassClusters, RSCAndPoints.RSC, OS);
702     OS << "<p>llvm SchedModel data:</p>";
703     printSchedClassDescHtml(RSCAndPoints.RSC, OS);
704     OS << "</div>";
705   }
706 
707   OS << "</body></html>";
708   return llvm::Error::success();
709 }
710 
711 // Distributes a pressure budget as evenly as possible on the provided subunits
712 // given the already existing port pressure distribution.
713 //
714 // The algorithm is as follows: while there is remaining pressure to
715 // distribute, find the subunits with minimal pressure, and distribute
716 // remaining pressure equally up to the pressure of the unit with
717 // second-to-minimal pressure.
718 // For example, let's assume we want to distribute 2*P1256
719 // (Subunits = [P1,P2,P5,P6]), and the starting DensePressure is:
720 //     DensePressure =        P0   P1   P2   P3   P4   P5   P6   P7
721 //                           0.1  0.3  0.2  0.0  0.0  0.5  0.5  0.5
722 //     RemainingPressure = 2.0
723 // We sort the subunits by pressure:
724 //     Subunits = [(P2,p=0.2), (P1,p=0.3), (P5,p=0.5), (P6, p=0.5)]
725 // We'll first start by the subunits with minimal pressure, which are at
726 // the beginning of the sorted array. In this example there is one (P2).
727 // The subunit with second-to-minimal pressure is the next one in the
728 // array (P1). So we distribute 0.1 pressure to P2, and remove 0.1 cycles
729 // from the budget.
730 //     Subunits = [(P2,p=0.3), (P1,p=0.3), (P5,p=0.5), (P5,p=0.5)]
731 //     RemainingPressure = 1.9
732 // We repeat this process: distribute 0.2 pressure on each of the minimal
733 // P2 and P1, decrease budget by 2*0.2:
734 //     Subunits = [(P2,p=0.5), (P1,p=0.5), (P5,p=0.5), (P5,p=0.5)]
735 //     RemainingPressure = 1.5
736 // There are no second-to-minimal subunits so we just share the remaining
737 // budget (1.5 cycles) equally:
738 //     Subunits = [(P2,p=0.875), (P1,p=0.875), (P5,p=0.875), (P5,p=0.875)]
739 //     RemainingPressure = 0.0
740 // We stop as there is no remaining budget to distribute.
741 void distributePressure(float RemainingPressure,
742                         llvm::SmallVector<uint16_t, 32> Subunits,
743                         llvm::SmallVector<float, 32> &DensePressure) {
744   // Find the number of subunits with minimal pressure (they are at the
745   // front).
746   llvm::sort(Subunits, [&DensePressure](const uint16_t A, const uint16_t B) {
747     return DensePressure[A] < DensePressure[B];
748   });
749   const auto getPressureForSubunit = [&DensePressure,
750                                       &Subunits](size_t I) -> float & {
751     return DensePressure[Subunits[I]];
752   };
753   size_t NumMinimalSU = 1;
754   while (NumMinimalSU < Subunits.size() &&
755          getPressureForSubunit(NumMinimalSU) == getPressureForSubunit(0)) {
756     ++NumMinimalSU;
757   }
758   while (RemainingPressure > 0.0f) {
759     if (NumMinimalSU == Subunits.size()) {
760       // All units are minimal, just distribute evenly and be done.
761       for (size_t I = 0; I < NumMinimalSU; ++I) {
762         getPressureForSubunit(I) += RemainingPressure / NumMinimalSU;
763       }
764       return;
765     }
766     // Distribute the remaining pressure equally.
767     const float MinimalPressure = getPressureForSubunit(NumMinimalSU - 1);
768     const float SecondToMinimalPressure = getPressureForSubunit(NumMinimalSU);
769     assert(MinimalPressure < SecondToMinimalPressure);
770     const float Increment = SecondToMinimalPressure - MinimalPressure;
771     if (RemainingPressure <= NumMinimalSU * Increment) {
772       // There is not enough remaining pressure.
773       for (size_t I = 0; I < NumMinimalSU; ++I) {
774         getPressureForSubunit(I) += RemainingPressure / NumMinimalSU;
775       }
776       return;
777     }
778     // Bump all minimal pressure subunits to `SecondToMinimalPressure`.
779     for (size_t I = 0; I < NumMinimalSU; ++I) {
780       getPressureForSubunit(I) = SecondToMinimalPressure;
781       RemainingPressure -= SecondToMinimalPressure;
782     }
783     while (NumMinimalSU < Subunits.size() &&
784            getPressureForSubunit(NumMinimalSU) == SecondToMinimalPressure) {
785       ++NumMinimalSU;
786     }
787   }
788 }
789 
790 std::vector<std::pair<uint16_t, float>> computeIdealizedProcResPressure(
791     const llvm::MCSchedModel &SM,
792     llvm::SmallVector<llvm::MCWriteProcResEntry, 8> WPRS) {
793   // DensePressure[I] is the port pressure for Proc Resource I.
794   llvm::SmallVector<float, 32> DensePressure(SM.getNumProcResourceKinds());
795   llvm::sort(WPRS, [](const llvm::MCWriteProcResEntry &A,
796                       const llvm::MCWriteProcResEntry &B) {
797     return A.ProcResourceIdx < B.ProcResourceIdx;
798   });
799   for (const llvm::MCWriteProcResEntry &WPR : WPRS) {
800     // Get units for the entry.
801     const llvm::MCProcResourceDesc *const ProcResDesc =
802         SM.getProcResource(WPR.ProcResourceIdx);
803     if (ProcResDesc->SubUnitsIdxBegin == nullptr) {
804       // This is a ProcResUnit.
805       DensePressure[WPR.ProcResourceIdx] += WPR.Cycles;
806     } else {
807       // This is a ProcResGroup.
808       llvm::SmallVector<uint16_t, 32> Subunits(ProcResDesc->SubUnitsIdxBegin,
809                                                ProcResDesc->SubUnitsIdxBegin +
810                                                    ProcResDesc->NumUnits);
811       distributePressure(WPR.Cycles, Subunits, DensePressure);
812     }
813   }
814   // Turn dense pressure into sparse pressure by removing zero entries.
815   std::vector<std::pair<uint16_t, float>> Pressure;
816   for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I) {
817     if (DensePressure[I] > 0.0f)
818       Pressure.emplace_back(I, DensePressure[I]);
819   }
820   return Pressure;
821 }
822 
823 } // namespace exegesis
824 } // namespace llvm
825