BenchmarkResult.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. //===-- BenchmarkResult.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. #include "BenchmarkResult.h"
  9. #include "BenchmarkRunner.h"
  10. #include "Error.h"
  11. #include "llvm/ADT/STLExtras.h"
  12. #include "llvm/ADT/ScopeExit.h"
  13. #include "llvm/ADT/StringMap.h"
  14. #include "llvm/ADT/StringRef.h"
  15. #include "llvm/ADT/bit.h"
  16. #include "llvm/ObjectYAML/YAML.h"
  17. #include "llvm/Support/FileOutputBuffer.h"
  18. #include "llvm/Support/FileSystem.h"
  19. #include "llvm/Support/Format.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. static constexpr const char kIntegerPrefix[] = "i_0x";
  22. static constexpr const char kDoublePrefix[] = "f_";
  23. static constexpr const char kInvalidOperand[] = "INVALID";
  24. static constexpr llvm::StringLiteral kNoRegister("%noreg");
  25. namespace llvm {
  26. namespace {
  27. // A mutable struct holding an LLVMState that can be passed through the
  28. // serialization process to encode/decode registers and instructions.
  29. struct YamlContext {
  30. YamlContext(const exegesis::LLVMState &State)
  31. : State(&State), ErrorStream(LastError),
  32. OpcodeNameToOpcodeIdx(
  33. generateOpcodeNameToOpcodeIdxMapping(State.getInstrInfo())),
  34. RegNameToRegNo(generateRegNameToRegNoMapping(State.getRegInfo())) {}
  35. static StringMap<unsigned>
  36. generateOpcodeNameToOpcodeIdxMapping(const MCInstrInfo &InstrInfo) {
  37. StringMap<unsigned> Map(InstrInfo.getNumOpcodes());
  38. for (unsigned I = 0, E = InstrInfo.getNumOpcodes(); I < E; ++I)
  39. Map[InstrInfo.getName(I)] = I;
  40. assert(Map.size() == InstrInfo.getNumOpcodes() && "Size prediction failed");
  41. return Map;
  42. };
  43. StringMap<unsigned>
  44. generateRegNameToRegNoMapping(const MCRegisterInfo &RegInfo) {
  45. StringMap<unsigned> Map(RegInfo.getNumRegs());
  46. // Special-case RegNo 0, which would otherwise be spelled as ''.
  47. Map[kNoRegister] = 0;
  48. for (unsigned I = 1, E = RegInfo.getNumRegs(); I < E; ++I)
  49. Map[RegInfo.getName(I)] = I;
  50. assert(Map.size() == RegInfo.getNumRegs() && "Size prediction failed");
  51. return Map;
  52. };
  53. void serializeMCInst(const MCInst &MCInst, raw_ostream &OS) {
  54. OS << getInstrName(MCInst.getOpcode());
  55. for (const auto &Op : MCInst) {
  56. OS << ' ';
  57. serializeMCOperand(Op, OS);
  58. }
  59. }
  60. void deserializeMCInst(StringRef String, MCInst &Value) {
  61. SmallVector<StringRef, 16> Pieces;
  62. String.split(Pieces, " ", /* MaxSplit */ -1, /* KeepEmpty */ false);
  63. if (Pieces.empty()) {
  64. ErrorStream << "Unknown Instruction: '" << String << "'\n";
  65. return;
  66. }
  67. bool ProcessOpcode = true;
  68. for (StringRef Piece : Pieces) {
  69. if (ProcessOpcode)
  70. Value.setOpcode(getInstrOpcode(Piece));
  71. else
  72. Value.addOperand(deserializeMCOperand(Piece));
  73. ProcessOpcode = false;
  74. }
  75. }
  76. std::string &getLastError() { return ErrorStream.str(); }
  77. raw_string_ostream &getErrorStream() { return ErrorStream; }
  78. StringRef getRegName(unsigned RegNo) {
  79. // Special case: RegNo 0 is NoRegister. We have to deal with it explicitly.
  80. if (RegNo == 0)
  81. return kNoRegister;
  82. const StringRef RegName = State->getRegInfo().getName(RegNo);
  83. if (RegName.empty())
  84. ErrorStream << "No register with enum value '" << RegNo << "'\n";
  85. return RegName;
  86. }
  87. Optional<unsigned> getRegNo(StringRef RegName) {
  88. auto Iter = RegNameToRegNo.find(RegName);
  89. if (Iter != RegNameToRegNo.end())
  90. return Iter->second;
  91. ErrorStream << "No register with name '" << RegName << "'\n";
  92. return None;
  93. }
  94. private:
  95. void serializeIntegerOperand(raw_ostream &OS, int64_t Value) {
  96. OS << kIntegerPrefix;
  97. OS.write_hex(bit_cast<uint64_t>(Value));
  98. }
  99. bool tryDeserializeIntegerOperand(StringRef String, int64_t &Value) {
  100. if (!String.consume_front(kIntegerPrefix))
  101. return false;
  102. return !String.consumeInteger(16, Value);
  103. }
  104. void serializeFPOperand(raw_ostream &OS, double Value) {
  105. OS << kDoublePrefix << format("%la", Value);
  106. }
  107. bool tryDeserializeFPOperand(StringRef String, double &Value) {
  108. if (!String.consume_front(kDoublePrefix))
  109. return false;
  110. char *EndPointer = nullptr;
  111. Value = strtod(String.begin(), &EndPointer);
  112. return EndPointer == String.end();
  113. }
  114. void serializeMCOperand(const MCOperand &MCOperand, raw_ostream &OS) {
  115. if (MCOperand.isReg()) {
  116. OS << getRegName(MCOperand.getReg());
  117. } else if (MCOperand.isImm()) {
  118. serializeIntegerOperand(OS, MCOperand.getImm());
  119. } else if (MCOperand.isDFPImm()) {
  120. serializeFPOperand(OS, bit_cast<double>(MCOperand.getDFPImm()));
  121. } else {
  122. OS << kInvalidOperand;
  123. }
  124. }
  125. MCOperand deserializeMCOperand(StringRef String) {
  126. assert(!String.empty());
  127. int64_t IntValue = 0;
  128. double DoubleValue = 0;
  129. if (tryDeserializeIntegerOperand(String, IntValue))
  130. return MCOperand::createImm(IntValue);
  131. if (tryDeserializeFPOperand(String, DoubleValue))
  132. return MCOperand::createDFPImm(bit_cast<uint64_t>(DoubleValue));
  133. if (auto RegNo = getRegNo(String))
  134. return MCOperand::createReg(*RegNo);
  135. if (String != kInvalidOperand)
  136. ErrorStream << "Unknown Operand: '" << String << "'\n";
  137. return {};
  138. }
  139. StringRef getInstrName(unsigned InstrNo) {
  140. const StringRef InstrName = State->getInstrInfo().getName(InstrNo);
  141. if (InstrName.empty())
  142. ErrorStream << "No opcode with enum value '" << InstrNo << "'\n";
  143. return InstrName;
  144. }
  145. unsigned getInstrOpcode(StringRef InstrName) {
  146. auto Iter = OpcodeNameToOpcodeIdx.find(InstrName);
  147. if (Iter != OpcodeNameToOpcodeIdx.end())
  148. return Iter->second;
  149. ErrorStream << "No opcode with name '" << InstrName << "'\n";
  150. return 0;
  151. }
  152. const exegesis::LLVMState *State;
  153. std::string LastError;
  154. raw_string_ostream ErrorStream;
  155. const StringMap<unsigned> OpcodeNameToOpcodeIdx;
  156. const StringMap<unsigned> RegNameToRegNo;
  157. };
  158. } // namespace
  159. // Defining YAML traits for IO.
  160. namespace yaml {
  161. static YamlContext &getTypedContext(void *Ctx) {
  162. return *reinterpret_cast<YamlContext *>(Ctx);
  163. }
  164. // std::vector<MCInst> will be rendered as a list.
  165. template <> struct SequenceElementTraits<MCInst> {
  166. static const bool flow = false;
  167. };
  168. template <> struct ScalarTraits<MCInst> {
  169. static void output(const MCInst &Value, void *Ctx, raw_ostream &Out) {
  170. getTypedContext(Ctx).serializeMCInst(Value, Out);
  171. }
  172. static StringRef input(StringRef Scalar, void *Ctx, MCInst &Value) {
  173. YamlContext &Context = getTypedContext(Ctx);
  174. Context.deserializeMCInst(Scalar, Value);
  175. return Context.getLastError();
  176. }
  177. // By default strings are quoted only when necessary.
  178. // We force the use of single quotes for uniformity.
  179. static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
  180. static const bool flow = true;
  181. };
  182. // std::vector<exegesis::Measure> will be rendered as a list.
  183. template <> struct SequenceElementTraits<exegesis::BenchmarkMeasure> {
  184. static const bool flow = false;
  185. };
  186. // exegesis::Measure is rendererd as a flow instead of a list.
  187. // e.g. { "key": "the key", "value": 0123 }
  188. template <> struct MappingTraits<exegesis::BenchmarkMeasure> {
  189. static void mapping(IO &Io, exegesis::BenchmarkMeasure &Obj) {
  190. Io.mapRequired("key", Obj.Key);
  191. if (!Io.outputting()) {
  192. // For backward compatibility, interpret debug_string as a key.
  193. Io.mapOptional("debug_string", Obj.Key);
  194. }
  195. Io.mapRequired("value", Obj.PerInstructionValue);
  196. Io.mapOptional("per_snippet_value", Obj.PerSnippetValue);
  197. }
  198. static const bool flow = true;
  199. };
  200. template <>
  201. struct ScalarEnumerationTraits<exegesis::InstructionBenchmark::ModeE> {
  202. static void enumeration(IO &Io,
  203. exegesis::InstructionBenchmark::ModeE &Value) {
  204. Io.enumCase(Value, "", exegesis::InstructionBenchmark::Unknown);
  205. Io.enumCase(Value, "latency", exegesis::InstructionBenchmark::Latency);
  206. Io.enumCase(Value, "uops", exegesis::InstructionBenchmark::Uops);
  207. Io.enumCase(Value, "inverse_throughput",
  208. exegesis::InstructionBenchmark::InverseThroughput);
  209. }
  210. };
  211. // std::vector<exegesis::RegisterValue> will be rendered as a list.
  212. template <> struct SequenceElementTraits<exegesis::RegisterValue> {
  213. static const bool flow = false;
  214. };
  215. template <> struct ScalarTraits<exegesis::RegisterValue> {
  216. static constexpr const unsigned kRadix = 16;
  217. static constexpr const bool kSigned = false;
  218. static void output(const exegesis::RegisterValue &RV, void *Ctx,
  219. raw_ostream &Out) {
  220. YamlContext &Context = getTypedContext(Ctx);
  221. Out << Context.getRegName(RV.Register) << "=0x"
  222. << toString(RV.Value, kRadix, kSigned);
  223. }
  224. static StringRef input(StringRef String, void *Ctx,
  225. exegesis::RegisterValue &RV) {
  226. SmallVector<StringRef, 2> Pieces;
  227. String.split(Pieces, "=0x", /* MaxSplit */ -1,
  228. /* KeepEmpty */ false);
  229. YamlContext &Context = getTypedContext(Ctx);
  230. Optional<unsigned> RegNo;
  231. if (Pieces.size() == 2 && (RegNo = Context.getRegNo(Pieces[0]))) {
  232. RV.Register = *RegNo;
  233. const unsigned BitsNeeded = APInt::getBitsNeeded(Pieces[1], kRadix);
  234. RV.Value = APInt(BitsNeeded, Pieces[1], kRadix);
  235. } else {
  236. Context.getErrorStream()
  237. << "Unknown initial register value: '" << String << "'";
  238. }
  239. return Context.getLastError();
  240. }
  241. static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
  242. static const bool flow = true;
  243. };
  244. template <>
  245. struct MappingContextTraits<exegesis::InstructionBenchmarkKey, YamlContext> {
  246. static void mapping(IO &Io, exegesis::InstructionBenchmarkKey &Obj,
  247. YamlContext &Context) {
  248. Io.setContext(&Context);
  249. Io.mapRequired("instructions", Obj.Instructions);
  250. Io.mapOptional("config", Obj.Config);
  251. Io.mapRequired("register_initial_values", Obj.RegisterInitialValues);
  252. }
  253. };
  254. template <>
  255. struct MappingContextTraits<exegesis::InstructionBenchmark, YamlContext> {
  256. struct NormalizedBinary {
  257. NormalizedBinary(IO &io) {}
  258. NormalizedBinary(IO &, std::vector<uint8_t> &Data) : Binary(Data) {}
  259. std::vector<uint8_t> denormalize(IO &) {
  260. std::vector<uint8_t> Data;
  261. std::string Str;
  262. raw_string_ostream OSS(Str);
  263. Binary.writeAsBinary(OSS);
  264. OSS.flush();
  265. Data.assign(Str.begin(), Str.end());
  266. return Data;
  267. }
  268. BinaryRef Binary;
  269. };
  270. static void mapping(IO &Io, exegesis::InstructionBenchmark &Obj,
  271. YamlContext &Context) {
  272. Io.mapRequired("mode", Obj.Mode);
  273. Io.mapRequired("key", Obj.Key, Context);
  274. Io.mapRequired("cpu_name", Obj.CpuName);
  275. Io.mapRequired("llvm_triple", Obj.LLVMTriple);
  276. Io.mapRequired("num_repetitions", Obj.NumRepetitions);
  277. Io.mapRequired("measurements", Obj.Measurements);
  278. Io.mapRequired("error", Obj.Error);
  279. Io.mapOptional("info", Obj.Info);
  280. // AssembledSnippet
  281. MappingNormalization<NormalizedBinary, std::vector<uint8_t>> BinaryString(
  282. Io, Obj.AssembledSnippet);
  283. Io.mapOptional("assembled_snippet", BinaryString->Binary);
  284. }
  285. };
  286. } // namespace yaml
  287. namespace exegesis {
  288. Expected<InstructionBenchmark>
  289. InstructionBenchmark::readYaml(const LLVMState &State, StringRef Filename) {
  290. if (auto ExpectedMemoryBuffer =
  291. errorOrToExpected(MemoryBuffer::getFile(Filename, /*IsText=*/true))) {
  292. yaml::Input Yin(*ExpectedMemoryBuffer.get());
  293. YamlContext Context(State);
  294. InstructionBenchmark Benchmark;
  295. if (Yin.setCurrentDocument())
  296. yaml::yamlize(Yin, Benchmark, /*unused*/ true, Context);
  297. if (!Context.getLastError().empty())
  298. return make_error<Failure>(Context.getLastError());
  299. return Benchmark;
  300. } else {
  301. return ExpectedMemoryBuffer.takeError();
  302. }
  303. }
  304. Expected<std::vector<InstructionBenchmark>>
  305. InstructionBenchmark::readYamls(const LLVMState &State, StringRef Filename) {
  306. if (auto ExpectedMemoryBuffer =
  307. errorOrToExpected(MemoryBuffer::getFile(Filename, /*IsText=*/true))) {
  308. yaml::Input Yin(*ExpectedMemoryBuffer.get());
  309. YamlContext Context(State);
  310. std::vector<InstructionBenchmark> Benchmarks;
  311. while (Yin.setCurrentDocument()) {
  312. Benchmarks.emplace_back();
  313. yamlize(Yin, Benchmarks.back(), /*unused*/ true, Context);
  314. if (Yin.error())
  315. return errorCodeToError(Yin.error());
  316. if (!Context.getLastError().empty())
  317. return make_error<Failure>(Context.getLastError());
  318. Yin.nextDocument();
  319. }
  320. return Benchmarks;
  321. } else {
  322. return ExpectedMemoryBuffer.takeError();
  323. }
  324. }
  325. Error InstructionBenchmark::writeYamlTo(const LLVMState &State,
  326. raw_ostream &OS) {
  327. auto Cleanup = make_scope_exit([&] { OS.flush(); });
  328. yaml::Output Yout(OS, nullptr /*Ctx*/, 200 /*WrapColumn*/);
  329. YamlContext Context(State);
  330. Yout.beginDocuments();
  331. yaml::yamlize(Yout, *this, /*unused*/ true, Context);
  332. if (!Context.getLastError().empty())
  333. return make_error<Failure>(Context.getLastError());
  334. Yout.endDocuments();
  335. return Error::success();
  336. }
  337. Error InstructionBenchmark::readYamlFrom(const LLVMState &State,
  338. StringRef InputContent) {
  339. yaml::Input Yin(InputContent);
  340. YamlContext Context(State);
  341. if (Yin.setCurrentDocument())
  342. yaml::yamlize(Yin, *this, /*unused*/ true, Context);
  343. if (!Context.getLastError().empty())
  344. return make_error<Failure>(Context.getLastError());
  345. return Error::success();
  346. }
  347. Error InstructionBenchmark::writeYaml(const LLVMState &State,
  348. const StringRef Filename) {
  349. if (Filename == "-") {
  350. if (auto Err = writeYamlTo(State, outs()))
  351. return Err;
  352. } else {
  353. int ResultFD = 0;
  354. if (auto E = errorCodeToError(openFileForWrite(Filename, ResultFD,
  355. sys::fs::CD_CreateAlways,
  356. sys::fs::OF_TextWithCRLF))) {
  357. return E;
  358. }
  359. raw_fd_ostream Ostr(ResultFD, true /*shouldClose*/);
  360. if (auto Err = writeYamlTo(State, Ostr))
  361. return Err;
  362. }
  363. return Error::success();
  364. }
  365. void PerInstructionStats::push(const BenchmarkMeasure &BM) {
  366. if (Key.empty())
  367. Key = BM.Key;
  368. assert(Key == BM.Key);
  369. ++NumValues;
  370. SumValues += BM.PerInstructionValue;
  371. MaxValue = std::max(MaxValue, BM.PerInstructionValue);
  372. MinValue = std::min(MinValue, BM.PerInstructionValue);
  373. }
  374. bool operator==(const BenchmarkMeasure &A, const BenchmarkMeasure &B) {
  375. return std::tie(A.Key, A.PerInstructionValue, A.PerSnippetValue) ==
  376. std::tie(B.Key, B.PerInstructionValue, B.PerSnippetValue);
  377. }
  378. } // namespace exegesis
  379. } // namespace llvm