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