Clang] Fix expansion of response files in -Wp after integrated-cc1 change
[llvm-project.git] / llvm / tools / llvm-exegesis / llvm-exegesis.cpp
blobc4574d38817d42eb02f33a557325deca3ec5e57b
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 SnippetOptions;
221 SnippetOptions.MaxConfigsPerOpcode = MaxConfigsPerOpcode;
222 const std::unique_ptr<SnippetGenerator> Generator =
223 State.getExegesisTarget().createSnippetGenerator(BenchmarkMode, State,
224 SnippetOptions);
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);
246 const std::unique_ptr<BenchmarkRunner> Runner =
247 State.getExegesisTarget().createBenchmarkRunner(BenchmarkMode, State);
248 if (!Runner) {
249 report_fatal_error("cannot create benchmark runner");
252 const auto Opcodes = getOpcodesOrDie(State.getInstrInfo());
254 const auto Repetitor = SnippetRepetitor::Create(RepetitionMode, State);
256 std::vector<BenchmarkCode> Configurations;
257 if (!Opcodes.empty()) {
258 for (const unsigned Opcode : Opcodes) {
259 // Ignore instructions without a sched class if
260 // -ignore-invalid-sched-class is passed.
261 if (IgnoreInvalidSchedClass &&
262 State.getInstrInfo().get(Opcode).getSchedClass() == 0) {
263 errs() << State.getInstrInfo().getName(Opcode)
264 << ": ignoring instruction without sched class\n";
265 continue;
267 auto ConfigsForInstr =
268 generateSnippets(State, Opcode, Repetitor->getReservedRegs());
269 if (!ConfigsForInstr) {
270 logAllUnhandledErrors(
271 ConfigsForInstr.takeError(), errs(),
272 Twine(State.getInstrInfo().getName(Opcode)).concat(": "));
273 continue;
275 std::move(ConfigsForInstr->begin(), ConfigsForInstr->end(),
276 std::back_inserter(Configurations));
278 } else {
279 Configurations = ExitOnErr(readSnippets(State, SnippetsFile));
282 if (NumRepetitions == 0)
283 report_fatal_error("--num-repetitions must be greater than zero");
285 // Write to standard output if file is not set.
286 if (BenchmarkFile.empty())
287 BenchmarkFile = "-";
289 for (const BenchmarkCode &Conf : Configurations) {
290 InstructionBenchmark Result = Runner->runConfiguration(
291 Conf, NumRepetitions, *Repetitor, DumpObjectToDisk);
292 ExitOnErr(Result.writeYaml(State, BenchmarkFile));
294 exegesis::pfm::pfmTerminate();
297 // Prints the results of running analysis pass `Pass` to file `OutputFilename`
298 // if OutputFilename is non-empty.
299 template <typename Pass>
300 static void maybeRunAnalysis(const Analysis &Analyzer, const std::string &Name,
301 const std::string &OutputFilename) {
302 if (OutputFilename.empty())
303 return;
304 if (OutputFilename != "-") {
305 errs() << "Printing " << Name << " results to file '" << OutputFilename
306 << "'\n";
308 std::error_code ErrorCode;
309 raw_fd_ostream ClustersOS(OutputFilename, ErrorCode,
310 sys::fs::FA_Read | sys::fs::FA_Write);
311 if (ErrorCode)
312 report_fatal_error("cannot open out file: " + OutputFilename);
313 if (auto Err = Analyzer.run<Pass>(ClustersOS))
314 report_fatal_error(std::move(Err));
317 static void analysisMain() {
318 if (BenchmarkFile.empty())
319 report_fatal_error("--benchmarks-file must be set.");
321 if (AnalysisClustersOutputFile.empty() &&
322 AnalysisInconsistenciesOutputFile.empty()) {
323 report_fatal_error(
324 "At least one of --analysis-clusters-output-file and "
325 "--analysis-inconsistencies-output-file must be specified.");
328 InitializeNativeTarget();
329 InitializeNativeTargetAsmPrinter();
330 InitializeNativeTargetDisassembler();
331 // Read benchmarks.
332 const LLVMState State("");
333 const std::vector<InstructionBenchmark> Points =
334 ExitOnErr(InstructionBenchmark::readYamls(State, BenchmarkFile));
335 outs() << "Parsed " << Points.size() << " benchmark points\n";
336 if (Points.empty()) {
337 errs() << "no benchmarks to analyze\n";
338 return;
340 // FIXME: Check that all points have the same triple/cpu.
341 // FIXME: Merge points from several runs (latency and uops).
343 std::string Error;
344 const auto *TheTarget =
345 TargetRegistry::lookupTarget(Points[0].LLVMTriple, Error);
346 if (!TheTarget) {
347 errs() << "unknown target '" << Points[0].LLVMTriple << "'\n";
348 return;
351 std::unique_ptr<MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
353 const auto Clustering = ExitOnErr(InstructionBenchmarkClustering::create(
354 Points, AnalysisClusteringAlgorithm, AnalysisDbscanNumPoints,
355 AnalysisClusteringEpsilon, InstrInfo->getNumOpcodes()));
357 const Analysis Analyzer(*TheTarget, std::move(InstrInfo), Clustering,
358 AnalysisInconsistencyEpsilon,
359 AnalysisDisplayUnstableOpcodes);
361 maybeRunAnalysis<Analysis::PrintClusters>(Analyzer, "analysis clusters",
362 AnalysisClustersOutputFile);
363 maybeRunAnalysis<Analysis::PrintSchedClassInconsistencies>(
364 Analyzer, "sched class consistency analysis",
365 AnalysisInconsistenciesOutputFile);
368 } // namespace exegesis
369 } // namespace llvm
371 int main(int Argc, char **Argv) {
372 using namespace llvm;
373 cl::ParseCommandLineOptions(Argc, Argv, "");
375 exegesis::ExitOnErr.setExitCodeMapper([](const Error &Err) {
376 if (Err.isA<StringError>())
377 return EXIT_SUCCESS;
378 return EXIT_FAILURE;
381 if (exegesis::BenchmarkMode == exegesis::InstructionBenchmark::Unknown) {
382 exegesis::analysisMain();
383 } else {
384 exegesis::benchmarkMain();
386 return EXIT_SUCCESS;