llvm-exegesis.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. //===----------------------------------------------------------------------===//
  13. #include "lib/Analysis.h"
  14. #include "lib/BenchmarkResult.h"
  15. #include "lib/BenchmarkRunner.h"
  16. #include "lib/Clustering.h"
  17. #include "lib/Error.h"
  18. #include "lib/LlvmState.h"
  19. #include "lib/PerfHelper.h"
  20. #include "lib/SnippetFile.h"
  21. #include "lib/SnippetRepetitor.h"
  22. #include "lib/Target.h"
  23. #include "lib/TargetSelect.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/ADT/Twine.h"
  26. #include "llvm/MC/MCInstBuilder.h"
  27. #include "llvm/MC/MCObjectFileInfo.h"
  28. #include "llvm/MC/MCParser/MCAsmParser.h"
  29. #include "llvm/MC/MCParser/MCTargetAsmParser.h"
  30. #include "llvm/MC/MCRegisterInfo.h"
  31. #include "llvm/MC/MCSubtargetInfo.h"
  32. #include "llvm/MC/TargetRegistry.h"
  33. #include "llvm/Object/ObjectFile.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Support/FileSystem.h"
  36. #include "llvm/Support/Format.h"
  37. #include "llvm/Support/Path.h"
  38. #include "llvm/Support/SourceMgr.h"
  39. #include "llvm/Support/TargetSelect.h"
  40. #include <algorithm>
  41. #include <string>
  42. namespace llvm {
  43. namespace exegesis {
  44. static cl::OptionCategory Options("llvm-exegesis options");
  45. static cl::OptionCategory BenchmarkOptions("llvm-exegesis benchmark options");
  46. static cl::OptionCategory AnalysisOptions("llvm-exegesis analysis options");
  47. static cl::opt<int> OpcodeIndex(
  48. "opcode-index",
  49. cl::desc("opcode to measure, by index, or -1 to measure all opcodes"),
  50. cl::cat(BenchmarkOptions), cl::init(0));
  51. static cl::opt<std::string>
  52. OpcodeNames("opcode-name",
  53. cl::desc("comma-separated list of opcodes to measure, by name"),
  54. cl::cat(BenchmarkOptions), cl::init(""));
  55. static cl::opt<std::string> SnippetsFile("snippets-file",
  56. cl::desc("code snippets to measure"),
  57. cl::cat(BenchmarkOptions),
  58. cl::init(""));
  59. static cl::opt<std::string>
  60. BenchmarkFile("benchmarks-file",
  61. cl::desc("File to read (analysis mode) or write "
  62. "(latency/uops/inverse_throughput modes) benchmark "
  63. "results. “-” uses stdin/stdout."),
  64. cl::cat(Options), cl::init(""));
  65. static cl::opt<exegesis::InstructionBenchmark::ModeE> BenchmarkMode(
  66. "mode", cl::desc("the mode to run"), cl::cat(Options),
  67. cl::values(clEnumValN(exegesis::InstructionBenchmark::Latency, "latency",
  68. "Instruction Latency"),
  69. clEnumValN(exegesis::InstructionBenchmark::InverseThroughput,
  70. "inverse_throughput",
  71. "Instruction Inverse Throughput"),
  72. clEnumValN(exegesis::InstructionBenchmark::Uops, "uops",
  73. "Uop Decomposition"),
  74. // When not asking for a specific benchmark mode,
  75. // we'll analyse the results.
  76. clEnumValN(exegesis::InstructionBenchmark::Unknown, "analysis",
  77. "Analysis")));
  78. static cl::opt<exegesis::InstructionBenchmark::ResultAggregationModeE>
  79. ResultAggMode(
  80. "result-aggregation-mode",
  81. cl::desc("How to aggregate multi-values result"), cl::cat(Options),
  82. cl::values(clEnumValN(exegesis::InstructionBenchmark::Min, "min",
  83. "Keep min reading"),
  84. clEnumValN(exegesis::InstructionBenchmark::Max, "max",
  85. "Keep max reading"),
  86. clEnumValN(exegesis::InstructionBenchmark::Mean, "mean",
  87. "Compute mean of all readings"),
  88. clEnumValN(exegesis::InstructionBenchmark::MinVariance,
  89. "min-variance",
  90. "Keep readings set with min-variance")),
  91. cl::init(exegesis::InstructionBenchmark::Min));
  92. static cl::opt<exegesis::InstructionBenchmark::RepetitionModeE> RepetitionMode(
  93. "repetition-mode", cl::desc("how to repeat the instruction snippet"),
  94. cl::cat(BenchmarkOptions),
  95. cl::values(
  96. clEnumValN(exegesis::InstructionBenchmark::Duplicate, "duplicate",
  97. "Duplicate the snippet"),
  98. clEnumValN(exegesis::InstructionBenchmark::Loop, "loop",
  99. "Loop over the snippet"),
  100. clEnumValN(exegesis::InstructionBenchmark::AggregateMin, "min",
  101. "All of the above and take the minimum of measurements")),
  102. cl::init(exegesis::InstructionBenchmark::Duplicate));
  103. static cl::opt<unsigned>
  104. NumRepetitions("num-repetitions",
  105. cl::desc("number of time to repeat the asm snippet"),
  106. cl::cat(BenchmarkOptions), cl::init(10000));
  107. static cl::opt<unsigned>
  108. LoopBodySize("loop-body-size",
  109. cl::desc("when repeating the instruction snippet by looping "
  110. "over it, duplicate the snippet until the loop body "
  111. "contains at least this many instruction"),
  112. cl::cat(BenchmarkOptions), cl::init(0));
  113. static cl::opt<unsigned> MaxConfigsPerOpcode(
  114. "max-configs-per-opcode",
  115. cl::desc(
  116. "allow to snippet generator to generate at most that many configs"),
  117. cl::cat(BenchmarkOptions), cl::init(1));
  118. static cl::opt<bool> IgnoreInvalidSchedClass(
  119. "ignore-invalid-sched-class",
  120. cl::desc("ignore instructions that do not define a sched class"),
  121. cl::cat(BenchmarkOptions), cl::init(false));
  122. static cl::opt<exegesis::InstructionBenchmarkClustering::ModeE>
  123. AnalysisClusteringAlgorithm(
  124. "analysis-clustering", cl::desc("the clustering algorithm to use"),
  125. cl::cat(AnalysisOptions),
  126. cl::values(clEnumValN(exegesis::InstructionBenchmarkClustering::Dbscan,
  127. "dbscan", "use DBSCAN/OPTICS algorithm"),
  128. clEnumValN(exegesis::InstructionBenchmarkClustering::Naive,
  129. "naive", "one cluster per opcode")),
  130. cl::init(exegesis::InstructionBenchmarkClustering::Dbscan));
  131. static cl::opt<unsigned> AnalysisDbscanNumPoints(
  132. "analysis-numpoints",
  133. cl::desc("minimum number of points in an analysis cluster (dbscan only)"),
  134. cl::cat(AnalysisOptions), cl::init(3));
  135. static cl::opt<float> AnalysisClusteringEpsilon(
  136. "analysis-clustering-epsilon",
  137. cl::desc("epsilon for benchmark point clustering"),
  138. cl::cat(AnalysisOptions), cl::init(0.1));
  139. static cl::opt<float> AnalysisInconsistencyEpsilon(
  140. "analysis-inconsistency-epsilon",
  141. cl::desc("epsilon for detection of when the cluster is different from the "
  142. "LLVM schedule profile values"),
  143. cl::cat(AnalysisOptions), cl::init(0.1));
  144. static cl::opt<std::string>
  145. AnalysisClustersOutputFile("analysis-clusters-output-file", cl::desc(""),
  146. cl::cat(AnalysisOptions), cl::init(""));
  147. static cl::opt<std::string>
  148. AnalysisInconsistenciesOutputFile("analysis-inconsistencies-output-file",
  149. cl::desc(""), cl::cat(AnalysisOptions),
  150. cl::init(""));
  151. static cl::opt<bool> AnalysisDisplayUnstableOpcodes(
  152. "analysis-display-unstable-clusters",
  153. cl::desc("if there is more than one benchmark for an opcode, said "
  154. "benchmarks may end up not being clustered into the same cluster "
  155. "if the measured performance characteristics are different. by "
  156. "default all such opcodes are filtered out. this flag will "
  157. "instead show only such unstable opcodes"),
  158. cl::cat(AnalysisOptions), cl::init(false));
  159. static cl::opt<std::string> CpuName(
  160. "mcpu",
  161. cl::desc("cpu name to use for pfm counters, leave empty to autodetect"),
  162. cl::cat(Options), cl::init(""));
  163. static cl::opt<bool>
  164. DumpObjectToDisk("dump-object-to-disk",
  165. cl::desc("dumps the generated benchmark object to disk "
  166. "and prints a message to access it"),
  167. cl::cat(BenchmarkOptions), cl::init(true));
  168. static ExitOnError ExitOnErr("llvm-exegesis error: ");
  169. // Helper function that logs the error(s) and exits.
  170. template <typename... ArgTs> static void ExitWithError(ArgTs &&... Args) {
  171. ExitOnErr(make_error<Failure>(std::forward<ArgTs>(Args)...));
  172. }
  173. // Check Err. If it's in a failure state log the file error(s) and exit.
  174. static void ExitOnFileError(const Twine &FileName, Error Err) {
  175. if (Err) {
  176. ExitOnErr(createFileError(FileName, std::move(Err)));
  177. }
  178. }
  179. // Check E. If it's in a success state then return the contained value.
  180. // If it's in a failure state log the file error(s) and exit.
  181. template <typename T>
  182. T ExitOnFileError(const Twine &FileName, Expected<T> &&E) {
  183. ExitOnFileError(FileName, E.takeError());
  184. return std::move(*E);
  185. }
  186. // Checks that only one of OpcodeNames, OpcodeIndex or SnippetsFile is provided,
  187. // and returns the opcode indices or {} if snippets should be read from
  188. // `SnippetsFile`.
  189. static std::vector<unsigned> getOpcodesOrDie(const MCInstrInfo &MCInstrInfo) {
  190. const size_t NumSetFlags = (OpcodeNames.empty() ? 0 : 1) +
  191. (OpcodeIndex == 0 ? 0 : 1) +
  192. (SnippetsFile.empty() ? 0 : 1);
  193. if (NumSetFlags != 1) {
  194. ExitOnErr.setBanner("llvm-exegesis: ");
  195. ExitWithError("please provide one and only one of 'opcode-index', "
  196. "'opcode-name' or 'snippets-file'");
  197. }
  198. if (!SnippetsFile.empty())
  199. return {};
  200. if (OpcodeIndex > 0)
  201. return {static_cast<unsigned>(OpcodeIndex)};
  202. if (OpcodeIndex < 0) {
  203. std::vector<unsigned> Result;
  204. for (unsigned I = 1, E = MCInstrInfo.getNumOpcodes(); I < E; ++I)
  205. Result.push_back(I);
  206. return Result;
  207. }
  208. // Resolve opcode name -> opcode.
  209. const auto ResolveName = [&MCInstrInfo](StringRef OpcodeName) -> unsigned {
  210. for (unsigned I = 1, E = MCInstrInfo.getNumOpcodes(); I < E; ++I)
  211. if (MCInstrInfo.getName(I) == OpcodeName)
  212. return I;
  213. return 0u;
  214. };
  215. SmallVector<StringRef, 2> Pieces;
  216. StringRef(OpcodeNames.getValue())
  217. .split(Pieces, ",", /* MaxSplit */ -1, /* KeepEmpty */ false);
  218. std::vector<unsigned> Result;
  219. for (const StringRef &OpcodeName : Pieces) {
  220. if (unsigned Opcode = ResolveName(OpcodeName))
  221. Result.push_back(Opcode);
  222. else
  223. ExitWithError(Twine("unknown opcode ").concat(OpcodeName));
  224. }
  225. return Result;
  226. }
  227. // Generates code snippets for opcode `Opcode`.
  228. static Expected<std::vector<BenchmarkCode>>
  229. generateSnippets(const LLVMState &State, unsigned Opcode,
  230. const BitVector &ForbiddenRegs) {
  231. const Instruction &Instr = State.getIC().getInstr(Opcode);
  232. const MCInstrDesc &InstrDesc = Instr.Description;
  233. // Ignore instructions that we cannot run.
  234. if (InstrDesc.isPseudo() || InstrDesc.usesCustomInsertionHook())
  235. return make_error<Failure>(
  236. "Unsupported opcode: isPseudo/usesCustomInserter");
  237. if (InstrDesc.isBranch() || InstrDesc.isIndirectBranch())
  238. return make_error<Failure>("Unsupported opcode: isBranch/isIndirectBranch");
  239. if (InstrDesc.isCall() || InstrDesc.isReturn())
  240. return make_error<Failure>("Unsupported opcode: isCall/isReturn");
  241. const std::vector<InstructionTemplate> InstructionVariants =
  242. State.getExegesisTarget().generateInstructionVariants(
  243. Instr, MaxConfigsPerOpcode);
  244. SnippetGenerator::Options SnippetOptions;
  245. SnippetOptions.MaxConfigsPerOpcode = MaxConfigsPerOpcode;
  246. const std::unique_ptr<SnippetGenerator> Generator =
  247. State.getExegesisTarget().createSnippetGenerator(BenchmarkMode, State,
  248. SnippetOptions);
  249. if (!Generator)
  250. ExitWithError("cannot create snippet generator");
  251. std::vector<BenchmarkCode> Benchmarks;
  252. for (const InstructionTemplate &Variant : InstructionVariants) {
  253. if (Benchmarks.size() >= MaxConfigsPerOpcode)
  254. break;
  255. if (auto Err = Generator->generateConfigurations(Variant, Benchmarks,
  256. ForbiddenRegs))
  257. return std::move(Err);
  258. }
  259. return Benchmarks;
  260. }
  261. void benchmarkMain() {
  262. #ifndef HAVE_LIBPFM
  263. ExitWithError("benchmarking unavailable, LLVM was built without libpfm.");
  264. #endif
  265. if (exegesis::pfm::pfmInitialize())
  266. ExitWithError("cannot initialize libpfm");
  267. InitializeNativeTarget();
  268. InitializeNativeTargetAsmPrinter();
  269. InitializeNativeTargetAsmParser();
  270. InitializeNativeExegesisTarget();
  271. const LLVMState State(CpuName);
  272. // Preliminary check to ensure features needed for requested
  273. // benchmark mode are present on target CPU and/or OS.
  274. ExitOnErr(State.getExegesisTarget().checkFeatureSupport());
  275. const std::unique_ptr<BenchmarkRunner> Runner =
  276. ExitOnErr(State.getExegesisTarget().createBenchmarkRunner(
  277. BenchmarkMode, State, ResultAggMode));
  278. if (!Runner) {
  279. ExitWithError("cannot create benchmark runner");
  280. }
  281. const auto Opcodes = getOpcodesOrDie(State.getInstrInfo());
  282. SmallVector<std::unique_ptr<const SnippetRepetitor>, 2> Repetitors;
  283. if (RepetitionMode != InstructionBenchmark::RepetitionModeE::AggregateMin)
  284. Repetitors.emplace_back(SnippetRepetitor::Create(RepetitionMode, State));
  285. else {
  286. for (InstructionBenchmark::RepetitionModeE RepMode :
  287. {InstructionBenchmark::RepetitionModeE::Duplicate,
  288. InstructionBenchmark::RepetitionModeE::Loop})
  289. Repetitors.emplace_back(SnippetRepetitor::Create(RepMode, State));
  290. }
  291. BitVector AllReservedRegs;
  292. llvm::for_each(Repetitors,
  293. [&AllReservedRegs](
  294. const std::unique_ptr<const SnippetRepetitor> &Repetitor) {
  295. AllReservedRegs |= Repetitor->getReservedRegs();
  296. });
  297. std::vector<BenchmarkCode> Configurations;
  298. if (!Opcodes.empty()) {
  299. for (const unsigned Opcode : Opcodes) {
  300. // Ignore instructions without a sched class if
  301. // -ignore-invalid-sched-class is passed.
  302. if (IgnoreInvalidSchedClass &&
  303. State.getInstrInfo().get(Opcode).getSchedClass() == 0) {
  304. errs() << State.getInstrInfo().getName(Opcode)
  305. << ": ignoring instruction without sched class\n";
  306. continue;
  307. }
  308. auto ConfigsForInstr = generateSnippets(State, Opcode, AllReservedRegs);
  309. if (!ConfigsForInstr) {
  310. logAllUnhandledErrors(
  311. ConfigsForInstr.takeError(), errs(),
  312. Twine(State.getInstrInfo().getName(Opcode)).concat(": "));
  313. continue;
  314. }
  315. std::move(ConfigsForInstr->begin(), ConfigsForInstr->end(),
  316. std::back_inserter(Configurations));
  317. }
  318. } else {
  319. Configurations = ExitOnErr(readSnippets(State, SnippetsFile));
  320. }
  321. if (NumRepetitions == 0) {
  322. ExitOnErr.setBanner("llvm-exegesis: ");
  323. ExitWithError("--num-repetitions must be greater than zero");
  324. }
  325. // Write to standard output if file is not set.
  326. if (BenchmarkFile.empty())
  327. BenchmarkFile = "-";
  328. for (const BenchmarkCode &Conf : Configurations) {
  329. InstructionBenchmark Result = ExitOnErr(Runner->runConfiguration(
  330. Conf, NumRepetitions, LoopBodySize, Repetitors, DumpObjectToDisk));
  331. ExitOnFileError(BenchmarkFile, Result.writeYaml(State, BenchmarkFile));
  332. }
  333. exegesis::pfm::pfmTerminate();
  334. }
  335. // Prints the results of running analysis pass `Pass` to file `OutputFilename`
  336. // if OutputFilename is non-empty.
  337. template <typename Pass>
  338. static void maybeRunAnalysis(const Analysis &Analyzer, const std::string &Name,
  339. const std::string &OutputFilename) {
  340. if (OutputFilename.empty())
  341. return;
  342. if (OutputFilename != "-") {
  343. errs() << "Printing " << Name << " results to file '" << OutputFilename
  344. << "'\n";
  345. }
  346. std::error_code ErrorCode;
  347. raw_fd_ostream ClustersOS(OutputFilename, ErrorCode,
  348. sys::fs::FA_Read | sys::fs::FA_Write);
  349. if (ErrorCode)
  350. ExitOnFileError(OutputFilename, errorCodeToError(ErrorCode));
  351. if (auto Err = Analyzer.run<Pass>(ClustersOS))
  352. ExitOnFileError(OutputFilename, std::move(Err));
  353. }
  354. static void analysisMain() {
  355. ExitOnErr.setBanner("llvm-exegesis: ");
  356. if (BenchmarkFile.empty())
  357. ExitWithError("--benchmarks-file must be set");
  358. if (AnalysisClustersOutputFile.empty() &&
  359. AnalysisInconsistenciesOutputFile.empty()) {
  360. ExitWithError(
  361. "for --mode=analysis: At least one of --analysis-clusters-output-file "
  362. "and --analysis-inconsistencies-output-file must be specified");
  363. }
  364. InitializeNativeTarget();
  365. InitializeNativeTargetAsmPrinter();
  366. InitializeNativeTargetDisassembler();
  367. // Read benchmarks.
  368. const LLVMState State("");
  369. const std::vector<InstructionBenchmark> Points = ExitOnFileError(
  370. BenchmarkFile, InstructionBenchmark::readYamls(State, BenchmarkFile));
  371. outs() << "Parsed " << Points.size() << " benchmark points\n";
  372. if (Points.empty()) {
  373. errs() << "no benchmarks to analyze\n";
  374. return;
  375. }
  376. // FIXME: Check that all points have the same triple/cpu.
  377. // FIXME: Merge points from several runs (latency and uops).
  378. std::string Error;
  379. const auto *TheTarget =
  380. TargetRegistry::lookupTarget(Points[0].LLVMTriple, Error);
  381. if (!TheTarget) {
  382. errs() << "unknown target '" << Points[0].LLVMTriple << "'\n";
  383. return;
  384. }
  385. std::unique_ptr<MCSubtargetInfo> SubtargetInfo(
  386. TheTarget->createMCSubtargetInfo(Points[0].LLVMTriple, CpuName, ""));
  387. std::unique_ptr<MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
  388. assert(InstrInfo && "Unable to create instruction info!");
  389. const auto Clustering = ExitOnErr(InstructionBenchmarkClustering::create(
  390. Points, AnalysisClusteringAlgorithm, AnalysisDbscanNumPoints,
  391. AnalysisClusteringEpsilon, SubtargetInfo.get(), InstrInfo.get()));
  392. const Analysis Analyzer(
  393. *TheTarget, std::move(SubtargetInfo), std::move(InstrInfo), Clustering,
  394. AnalysisInconsistencyEpsilon, AnalysisDisplayUnstableOpcodes, CpuName);
  395. maybeRunAnalysis<Analysis::PrintClusters>(Analyzer, "analysis clusters",
  396. AnalysisClustersOutputFile);
  397. maybeRunAnalysis<Analysis::PrintSchedClassInconsistencies>(
  398. Analyzer, "sched class consistency analysis",
  399. AnalysisInconsistenciesOutputFile);
  400. }
  401. } // namespace exegesis
  402. } // namespace llvm
  403. int main(int Argc, char **Argv) {
  404. using namespace llvm;
  405. cl::ParseCommandLineOptions(Argc, Argv, "");
  406. exegesis::ExitOnErr.setExitCodeMapper([](const Error &Err) {
  407. if (Err.isA<exegesis::ClusteringError>())
  408. return EXIT_SUCCESS;
  409. return EXIT_FAILURE;
  410. });
  411. if (exegesis::BenchmarkMode == exegesis::InstructionBenchmark::Unknown) {
  412. exegesis::analysisMain();
  413. } else {
  414. exegesis::benchmarkMain();
  415. }
  416. return EXIT_SUCCESS;
  417. }