[InstCombine] Signed saturation patterns
[llvm-core.git] / tools / llvm-exegesis / llvm-exegesis.cpp
blob04792e6376a2f361786819f6b7f39a2635df5d90
1 //===-- llvm-exegesis.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 /// \file
10 /// Measures execution properties (latencies/uops) of an instruction.
11 ///
12 //===----------------------------------------------------------------------===//
14 #include "lib/Analysis.h"
15 #include "lib/BenchmarkResult.h"
16 #include "lib/BenchmarkRunner.h"
17 #include "lib/Clustering.h"
18 #include "lib/Error.h"
19 #include "lib/LlvmState.h"
20 #include "lib/PerfHelper.h"
21 #include "lib/SnippetFile.h"
22 #include "lib/SnippetRepetitor.h"
23 #include "lib/Target.h"
24 #include "lib/TargetSelect.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/MC/MCInstBuilder.h"
28 #include "llvm/MC/MCObjectFileInfo.h"
29 #include "llvm/MC/MCParser/MCAsmParser.h"
30 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSubtargetInfo.h"
33 #include "llvm/Object/ObjectFile.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include <algorithm>
41 #include <string>
43 namespace llvm {
44 namespace exegesis {
46 static cl::OptionCategory Options("llvm-exegesis options");
47 static cl::OptionCategory BenchmarkOptions("llvm-exegesis benchmark options");
48 static cl::OptionCategory AnalysisOptions("llvm-exegesis analysis options");
50 static cl::opt<int> OpcodeIndex("opcode-index",
51 cl::desc("opcode to measure, by index"),
52 cl::cat(BenchmarkOptions), cl::init(0));
54 static cl::opt<std::string>
55 OpcodeNames("opcode-name",
56 cl::desc("comma-separated list of opcodes to measure, by name"),
57 cl::cat(BenchmarkOptions), cl::init(""));
59 static cl::opt<std::string> SnippetsFile("snippets-file",
60 cl::desc("code snippets to measure"),
61 cl::cat(BenchmarkOptions),
62 cl::init(""));
64 static cl::opt<std::string>
65 BenchmarkFile("benchmarks-file",
66 cl::desc("File to read (analysis mode) or write "
67 "(latency/uops/inverse_throughput modes) benchmark "
68 "results. “-” uses stdin/stdout."),
69 cl::cat(Options), cl::init(""));
71 static cl::opt<exegesis::InstructionBenchmark::ModeE> BenchmarkMode(
72 "mode", cl::desc("the mode to run"), cl::cat(Options),
73 cl::values(clEnumValN(exegesis::InstructionBenchmark::Latency, "latency",
74 "Instruction Latency"),
75 clEnumValN(exegesis::InstructionBenchmark::InverseThroughput,
76 "inverse_throughput",
77 "Instruction Inverse Throughput"),
78 clEnumValN(exegesis::InstructionBenchmark::Uops, "uops",
79 "Uop Decomposition"),
80 // When not asking for a specific benchmark mode,
81 // we'll analyse the results.
82 clEnumValN(exegesis::InstructionBenchmark::Unknown, "analysis",
83 "Analysis")));
85 static cl::opt<exegesis::InstructionBenchmark::RepetitionModeE> RepetitionMode(
86 "repetition-mode", cl::desc("how to repeat the instruction snippet"),
87 cl::cat(BenchmarkOptions),
88 cl::values(clEnumValN(exegesis::InstructionBenchmark::Duplicate,
89 "duplicate", "Duplicate the snippet"),
90 clEnumValN(exegesis::InstructionBenchmark::Loop, "loop",
91 "Loop over the snippet")));
93 static cl::opt<unsigned>
94 NumRepetitions("num-repetitions",
95 cl::desc("number of time to repeat the asm snippet"),
96 cl::cat(BenchmarkOptions), cl::init(10000));
98 static cl::opt<unsigned> MaxConfigsPerOpcode(
99 "max-configs-per-opcode",
100 cl::desc(
101 "allow to snippet generator to generate at most that many configs"),
102 cl::cat(BenchmarkOptions), cl::init(1));
104 static cl::opt<bool> IgnoreInvalidSchedClass(
105 "ignore-invalid-sched-class",
106 cl::desc("ignore instructions that do not define a sched class"),
107 cl::cat(BenchmarkOptions), cl::init(false));
109 static cl::opt<exegesis::InstructionBenchmarkClustering::ModeE>
110 AnalysisClusteringAlgorithm(
111 "analysis-clustering", cl::desc("the clustering algorithm to use"),
112 cl::cat(AnalysisOptions),
113 cl::values(clEnumValN(exegesis::InstructionBenchmarkClustering::Dbscan,
114 "dbscan", "use DBSCAN/OPTICS algorithm"),
115 clEnumValN(exegesis::InstructionBenchmarkClustering::Naive,
116 "naive", "one cluster per opcode")),
117 cl::init(exegesis::InstructionBenchmarkClustering::Dbscan));
119 static cl::opt<unsigned> AnalysisDbscanNumPoints(
120 "analysis-numpoints",
121 cl::desc("minimum number of points in an analysis cluster (dbscan only)"),
122 cl::cat(AnalysisOptions), cl::init(3));
124 static cl::opt<float> AnalysisClusteringEpsilon(
125 "analysis-clustering-epsilon",
126 cl::desc("epsilon for benchmark point clustering"),
127 cl::cat(AnalysisOptions), cl::init(0.1));
129 static cl::opt<float> AnalysisInconsistencyEpsilon(
130 "analysis-inconsistency-epsilon",
131 cl::desc("epsilon for detection of when the cluster is different from the "
132 "LLVM schedule profile values"),
133 cl::cat(AnalysisOptions), cl::init(0.1));
135 static cl::opt<std::string>
136 AnalysisClustersOutputFile("analysis-clusters-output-file", cl::desc(""),
137 cl::cat(AnalysisOptions), cl::init(""));
138 static cl::opt<std::string>
139 AnalysisInconsistenciesOutputFile("analysis-inconsistencies-output-file",
140 cl::desc(""), cl::cat(AnalysisOptions),
141 cl::init(""));
143 static cl::opt<bool> AnalysisDisplayUnstableOpcodes(
144 "analysis-display-unstable-clusters",
145 cl::desc("if there is more than one benchmark for an opcode, said "
146 "benchmarks may end up not being clustered into the same cluster "
147 "if the measured performance characteristics are different. by "
148 "default all such opcodes are filtered out. this flag will "
149 "instead show only such unstable opcodes"),
150 cl::cat(AnalysisOptions), cl::init(false));
152 static cl::opt<std::string> CpuName(
153 "mcpu",
154 cl::desc("cpu name to use for pfm counters, leave empty to autodetect"),
155 cl::cat(Options), cl::init(""));
157 static cl::opt<bool>
158 DumpObjectToDisk("dump-object-to-disk",
159 cl::desc("dumps the generated benchmark object to disk "
160 "and prints a message to access it"),
161 cl::cat(BenchmarkOptions), cl::init(true));
163 static ExitOnError ExitOnErr;
165 // Checks that only one of OpcodeNames, OpcodeIndex or SnippetsFile is provided,
166 // and returns the opcode indices or {} if snippets should be read from
167 // `SnippetsFile`.
168 static std::vector<unsigned> getOpcodesOrDie(const MCInstrInfo &MCInstrInfo) {
169 const size_t NumSetFlags = (OpcodeNames.empty() ? 0 : 1) +
170 (OpcodeIndex == 0 ? 0 : 1) +
171 (SnippetsFile.empty() ? 0 : 1);
172 if (NumSetFlags != 1)
173 report_fatal_error(
174 "please provide one and only one of 'opcode-index', 'opcode-name' or "
175 "'snippets-file'");
176 if (!SnippetsFile.empty())
177 return {};
178 if (OpcodeIndex > 0)
179 return {static_cast<unsigned>(OpcodeIndex)};
180 if (OpcodeIndex < 0) {
181 std::vector<unsigned> Result;
182 for (unsigned I = 1, E = MCInstrInfo.getNumOpcodes(); I < E; ++I)
183 Result.push_back(I);
184 return Result;
186 // Resolve opcode name -> opcode.
187 const auto ResolveName = [&MCInstrInfo](StringRef OpcodeName) -> unsigned {
188 for (unsigned I = 1, E = MCInstrInfo.getNumOpcodes(); I < E; ++I)
189 if (MCInstrInfo.getName(I) == OpcodeName)
190 return I;
191 return 0u;
193 SmallVector<StringRef, 2> Pieces;
194 StringRef(OpcodeNames.getValue())
195 .split(Pieces, ",", /* MaxSplit */ -1, /* KeepEmpty */ false);
196 std::vector<unsigned> Result;
197 for (const StringRef OpcodeName : Pieces) {
198 if (unsigned Opcode = ResolveName(OpcodeName))
199 Result.push_back(Opcode);
200 else
201 report_fatal_error(Twine("unknown opcode ").concat(OpcodeName));
203 return Result;
206 // Generates code snippets for opcode `Opcode`.
207 static Expected<std::vector<BenchmarkCode>>
208 generateSnippets(const LLVMState &State, unsigned Opcode,
209 const BitVector &ForbiddenRegs) {
210 const Instruction &Instr = State.getIC().getInstr(Opcode);
211 const MCInstrDesc &InstrDesc = *Instr.Description;
212 // Ignore instructions that we cannot run.
213 if (InstrDesc.isPseudo())
214 return make_error<Failure>("Unsupported opcode: isPseudo");
215 if (InstrDesc.isBranch() || InstrDesc.isIndirectBranch())
216 return make_error<Failure>("Unsupported opcode: isBranch/isIndirectBranch");
217 if (InstrDesc.isCall() || InstrDesc.isReturn())
218 return make_error<Failure>("Unsupported opcode: isCall/isReturn");
220 SnippetGenerator::Options Options;
221 Options.MaxConfigsPerOpcode = MaxConfigsPerOpcode;
222 const std::unique_ptr<SnippetGenerator> Generator =
223 State.getExegesisTarget().createSnippetGenerator(BenchmarkMode, State,
224 Options);
225 if (!Generator)
226 report_fatal_error("cannot create snippet generator");
227 return Generator->generateConfigurations(Instr, ForbiddenRegs);
230 void benchmarkMain() {
231 #ifndef HAVE_LIBPFM
232 report_fatal_error(
233 "benchmarking unavailable, LLVM was built without libpfm.");
234 #endif
236 if (exegesis::pfm::pfmInitialize())
237 report_fatal_error("cannot initialize libpfm");
239 InitializeNativeTarget();
240 InitializeNativeTargetAsmPrinter();
241 InitializeNativeTargetAsmParser();
242 InitializeNativeExegesisTarget();
244 const LLVMState State(CpuName);
245 const auto Opcodes = getOpcodesOrDie(State.getInstrInfo());
247 const auto Repetitor = SnippetRepetitor::Create(RepetitionMode, State);
249 std::vector<BenchmarkCode> Configurations;
250 if (!Opcodes.empty()) {
251 for (const unsigned Opcode : Opcodes) {
252 // Ignore instructions without a sched class if
253 // -ignore-invalid-sched-class is passed.
254 if (IgnoreInvalidSchedClass &&
255 State.getInstrInfo().get(Opcode).getSchedClass() == 0) {
256 errs() << State.getInstrInfo().getName(Opcode)
257 << ": ignoring instruction without sched class\n";
258 continue;
260 auto ConfigsForInstr =
261 generateSnippets(State, Opcode, Repetitor->getReservedRegs());
262 if (!ConfigsForInstr) {
263 logAllUnhandledErrors(
264 ConfigsForInstr.takeError(), errs(),
265 Twine(State.getInstrInfo().getName(Opcode)).concat(": "));
266 continue;
268 std::move(ConfigsForInstr->begin(), ConfigsForInstr->end(),
269 std::back_inserter(Configurations));
271 } else {
272 Configurations = ExitOnErr(readSnippets(State, SnippetsFile));
275 const std::unique_ptr<BenchmarkRunner> Runner =
276 State.getExegesisTarget().createBenchmarkRunner(BenchmarkMode, State);
277 if (!Runner) {
278 report_fatal_error("cannot create benchmark runner");
281 if (NumRepetitions == 0)
282 report_fatal_error("--num-repetitions must be greater than zero");
284 // Write to standard output if file is not set.
285 if (BenchmarkFile.empty())
286 BenchmarkFile = "-";
288 for (const BenchmarkCode &Conf : Configurations) {
289 InstructionBenchmark Result = Runner->runConfiguration(
290 Conf, NumRepetitions, *Repetitor, DumpObjectToDisk);
291 ExitOnErr(Result.writeYaml(State, BenchmarkFile));
293 exegesis::pfm::pfmTerminate();
296 // Prints the results of running analysis pass `Pass` to file `OutputFilename`
297 // if OutputFilename is non-empty.
298 template <typename Pass>
299 static void maybeRunAnalysis(const Analysis &Analyzer, const std::string &Name,
300 const std::string &OutputFilename) {
301 if (OutputFilename.empty())
302 return;
303 if (OutputFilename != "-") {
304 errs() << "Printing " << Name << " results to file '" << OutputFilename
305 << "'\n";
307 std::error_code ErrorCode;
308 raw_fd_ostream ClustersOS(OutputFilename, ErrorCode,
309 sys::fs::FA_Read | sys::fs::FA_Write);
310 if (ErrorCode)
311 report_fatal_error("cannot open out file: " + OutputFilename);
312 if (auto Err = Analyzer.run<Pass>(ClustersOS))
313 report_fatal_error(std::move(Err));
316 static void analysisMain() {
317 if (BenchmarkFile.empty())
318 report_fatal_error("--benchmarks-file must be set.");
320 if (AnalysisClustersOutputFile.empty() &&
321 AnalysisInconsistenciesOutputFile.empty()) {
322 report_fatal_error(
323 "At least one of --analysis-clusters-output-file and "
324 "--analysis-inconsistencies-output-file must be specified.");
327 InitializeNativeTarget();
328 InitializeNativeTargetAsmPrinter();
329 InitializeNativeTargetDisassembler();
330 // Read benchmarks.
331 const LLVMState State("");
332 const std::vector<InstructionBenchmark> Points =
333 ExitOnErr(InstructionBenchmark::readYamls(State, BenchmarkFile));
334 outs() << "Parsed " << Points.size() << " benchmark points\n";
335 if (Points.empty()) {
336 errs() << "no benchmarks to analyze\n";
337 return;
339 // FIXME: Check that all points have the same triple/cpu.
340 // FIXME: Merge points from several runs (latency and uops).
342 std::string Error;
343 const auto *TheTarget =
344 TargetRegistry::lookupTarget(Points[0].LLVMTriple, Error);
345 if (!TheTarget) {
346 errs() << "unknown target '" << Points[0].LLVMTriple << "'\n";
347 return;
350 std::unique_ptr<MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
352 const auto Clustering = ExitOnErr(InstructionBenchmarkClustering::create(
353 Points, AnalysisClusteringAlgorithm, AnalysisDbscanNumPoints,
354 AnalysisClusteringEpsilon, InstrInfo->getNumOpcodes()));
356 const Analysis Analyzer(*TheTarget, std::move(InstrInfo), Clustering,
357 AnalysisInconsistencyEpsilon,
358 AnalysisDisplayUnstableOpcodes);
360 maybeRunAnalysis<Analysis::PrintClusters>(Analyzer, "analysis clusters",
361 AnalysisClustersOutputFile);
362 maybeRunAnalysis<Analysis::PrintSchedClassInconsistencies>(
363 Analyzer, "sched class consistency analysis",
364 AnalysisInconsistenciesOutputFile);
367 } // namespace exegesis
368 } // namespace llvm
370 int main(int Argc, char **Argv) {
371 using namespace llvm;
372 cl::ParseCommandLineOptions(Argc, Argv, "");
374 exegesis::ExitOnErr.setExitCodeMapper([](const Error &Err) {
375 if (Err.isA<StringError>())
376 return EXIT_SUCCESS;
377 return EXIT_FAILURE;
380 if (exegesis::BenchmarkMode == exegesis::InstructionBenchmark::Unknown) {
381 exegesis::analysisMain();
382 } else {
383 exegesis::benchmarkMain();
385 return EXIT_SUCCESS;