SnippetGenerator.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. //===-- SnippetGenerator.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 <array>
  9. #include <string>
  10. #include "Assembler.h"
  11. #include "Error.h"
  12. #include "MCInstrDescView.h"
  13. #include "SnippetGenerator.h"
  14. #include "Target.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Support/FileSystem.h"
  19. #include "llvm/Support/FormatVariadic.h"
  20. #include "llvm/Support/Program.h"
  21. namespace llvm {
  22. namespace exegesis {
  23. std::vector<CodeTemplate> getSingleton(CodeTemplate &&CT) {
  24. std::vector<CodeTemplate> Result;
  25. Result.push_back(std::move(CT));
  26. return Result;
  27. }
  28. SnippetGeneratorFailure::SnippetGeneratorFailure(const llvm::Twine &S)
  29. : llvm::StringError(S, llvm::inconvertibleErrorCode()) {}
  30. SnippetGenerator::SnippetGenerator(const LLVMState &State, const Options &Opts)
  31. : State(State), Opts(Opts) {}
  32. SnippetGenerator::~SnippetGenerator() = default;
  33. llvm::Expected<std::vector<BenchmarkCode>>
  34. SnippetGenerator::generateConfigurations(
  35. const Instruction &Instr, const llvm::BitVector &ExtraForbiddenRegs) const {
  36. llvm::BitVector ForbiddenRegs = State.getRATC().reservedRegisters();
  37. ForbiddenRegs |= ExtraForbiddenRegs;
  38. // If the instruction has memory registers, prevent the generator from
  39. // using the scratch register and its aliasing registers.
  40. if (Instr.hasMemoryOperands()) {
  41. const auto &ET = State.getExegesisTarget();
  42. unsigned ScratchSpacePointerInReg =
  43. ET.getScratchMemoryRegister(State.getTargetMachine().getTargetTriple());
  44. if (ScratchSpacePointerInReg == 0)
  45. return make_error<Failure>(
  46. "Infeasible : target does not support memory instructions");
  47. const auto &ScratchRegAliases =
  48. State.getRATC().getRegister(ScratchSpacePointerInReg).aliasedBits();
  49. // If the instruction implicitly writes to ScratchSpacePointerInReg , abort.
  50. // FIXME: We could make a copy of the scratch register.
  51. for (const auto &Op : Instr.Operands) {
  52. if (Op.isDef() && Op.isImplicitReg() &&
  53. ScratchRegAliases.test(Op.getImplicitReg()))
  54. return make_error<Failure>(
  55. "Infeasible : memory instruction uses scratch memory register");
  56. }
  57. ForbiddenRegs |= ScratchRegAliases;
  58. }
  59. if (auto E = generateCodeTemplates(Instr, ForbiddenRegs)) {
  60. std::vector<BenchmarkCode> Output;
  61. for (CodeTemplate &CT : E.get()) {
  62. // TODO: Generate as many BenchmarkCode as needed.
  63. {
  64. BenchmarkCode BC;
  65. BC.Info = CT.Info;
  66. for (InstructionTemplate &IT : CT.Instructions) {
  67. randomizeUnsetVariables(State.getExegesisTarget(), ForbiddenRegs, IT);
  68. BC.Key.Instructions.push_back(IT.build());
  69. }
  70. if (CT.ScratchSpacePointerInReg)
  71. BC.LiveIns.push_back(CT.ScratchSpacePointerInReg);
  72. BC.Key.RegisterInitialValues =
  73. computeRegisterInitialValues(CT.Instructions);
  74. BC.Key.Config = CT.Config;
  75. Output.push_back(std::move(BC));
  76. if (Output.size() >= Opts.MaxConfigsPerOpcode)
  77. return Output; // Early exit if we exceeded the number of allowed
  78. // configs.
  79. }
  80. }
  81. return Output;
  82. } else
  83. return E.takeError();
  84. }
  85. std::vector<RegisterValue> SnippetGenerator::computeRegisterInitialValues(
  86. const std::vector<InstructionTemplate> &Instructions) const {
  87. // Collect all register uses and create an assignment for each of them.
  88. // Ignore memory operands which are handled separately.
  89. // Loop invariant: DefinedRegs[i] is true iif it has been set at least once
  90. // before the current instruction.
  91. llvm::BitVector DefinedRegs = State.getRATC().emptyRegisters();
  92. std::vector<RegisterValue> RIV;
  93. for (const InstructionTemplate &IT : Instructions) {
  94. // Returns the register that this Operand sets or uses, or 0 if this is not
  95. // a register.
  96. const auto GetOpReg = [&IT](const Operand &Op) -> unsigned {
  97. if (Op.isMemory())
  98. return 0;
  99. if (Op.isImplicitReg())
  100. return Op.getImplicitReg();
  101. if (Op.isExplicit() && IT.getValueFor(Op).isReg())
  102. return IT.getValueFor(Op).getReg();
  103. return 0;
  104. };
  105. // Collect used registers that have never been def'ed.
  106. for (const Operand &Op : IT.Instr.Operands) {
  107. if (Op.isUse()) {
  108. const unsigned Reg = GetOpReg(Op);
  109. if (Reg > 0 && !DefinedRegs.test(Reg)) {
  110. RIV.push_back(RegisterValue::zero(Reg));
  111. DefinedRegs.set(Reg);
  112. }
  113. }
  114. }
  115. // Mark defs as having been def'ed.
  116. for (const Operand &Op : IT.Instr.Operands) {
  117. if (Op.isDef()) {
  118. const unsigned Reg = GetOpReg(Op);
  119. if (Reg > 0)
  120. DefinedRegs.set(Reg);
  121. }
  122. }
  123. }
  124. return RIV;
  125. }
  126. llvm::Expected<std::vector<CodeTemplate>>
  127. generateSelfAliasingCodeTemplates(const Instruction &Instr) {
  128. const AliasingConfigurations SelfAliasing(Instr, Instr);
  129. if (SelfAliasing.empty())
  130. return llvm::make_error<SnippetGeneratorFailure>("empty self aliasing");
  131. std::vector<CodeTemplate> Result;
  132. Result.emplace_back();
  133. CodeTemplate &CT = Result.back();
  134. InstructionTemplate IT(Instr);
  135. if (SelfAliasing.hasImplicitAliasing()) {
  136. CT.Info = "implicit Self cycles, picking random values.";
  137. } else {
  138. CT.Info = "explicit self cycles, selecting one aliasing Conf.";
  139. // This is a self aliasing instruction so defs and uses are from the same
  140. // instance, hence twice IT in the following call.
  141. setRandomAliasing(SelfAliasing, IT, IT);
  142. }
  143. CT.Instructions.push_back(std::move(IT));
  144. return std::move(Result);
  145. }
  146. llvm::Expected<std::vector<CodeTemplate>>
  147. generateUnconstrainedCodeTemplates(const Instruction &Instr,
  148. llvm::StringRef Msg) {
  149. std::vector<CodeTemplate> Result;
  150. Result.emplace_back();
  151. CodeTemplate &CT = Result.back();
  152. CT.Info = llvm::formatv("{0}, repeating an unconstrained assignment", Msg);
  153. CT.Instructions.emplace_back(Instr);
  154. return std::move(Result);
  155. }
  156. std::mt19937 &randomGenerator() {
  157. static std::random_device RandomDevice;
  158. static std::mt19937 RandomGenerator(RandomDevice());
  159. return RandomGenerator;
  160. }
  161. size_t randomIndex(size_t Max) {
  162. std::uniform_int_distribution<> Distribution(0, Max);
  163. return Distribution(randomGenerator());
  164. }
  165. template <typename C>
  166. static auto randomElement(const C &Container) -> decltype(Container[0]) {
  167. assert(!Container.empty() &&
  168. "Can't pick a random element from an empty container)");
  169. return Container[randomIndex(Container.size() - 1)];
  170. }
  171. static void setRegisterOperandValue(const RegisterOperandAssignment &ROV,
  172. InstructionTemplate &IB) {
  173. assert(ROV.Op);
  174. if (ROV.Op->isExplicit()) {
  175. auto &AssignedValue = IB.getValueFor(*ROV.Op);
  176. if (AssignedValue.isValid()) {
  177. assert(AssignedValue.isReg() && AssignedValue.getReg() == ROV.Reg);
  178. return;
  179. }
  180. AssignedValue = llvm::MCOperand::createReg(ROV.Reg);
  181. } else {
  182. assert(ROV.Op->isImplicitReg());
  183. assert(ROV.Reg == ROV.Op->getImplicitReg());
  184. }
  185. }
  186. size_t randomBit(const llvm::BitVector &Vector) {
  187. assert(Vector.any());
  188. auto Itr = Vector.set_bits_begin();
  189. for (size_t I = randomIndex(Vector.count() - 1); I != 0; --I)
  190. ++Itr;
  191. return *Itr;
  192. }
  193. void setRandomAliasing(const AliasingConfigurations &AliasingConfigurations,
  194. InstructionTemplate &DefIB, InstructionTemplate &UseIB) {
  195. assert(!AliasingConfigurations.empty());
  196. assert(!AliasingConfigurations.hasImplicitAliasing());
  197. const auto &RandomConf = randomElement(AliasingConfigurations.Configurations);
  198. setRegisterOperandValue(randomElement(RandomConf.Defs), DefIB);
  199. setRegisterOperandValue(randomElement(RandomConf.Uses), UseIB);
  200. }
  201. void randomizeUnsetVariables(const ExegesisTarget &Target,
  202. const llvm::BitVector &ForbiddenRegs,
  203. InstructionTemplate &IT) {
  204. for (const Variable &Var : IT.Instr.Variables) {
  205. llvm::MCOperand &AssignedValue = IT.getValueFor(Var);
  206. if (!AssignedValue.isValid())
  207. Target.randomizeMCOperand(IT.Instr, Var, AssignedValue, ForbiddenRegs);
  208. }
  209. }
  210. } // namespace exegesis
  211. } // namespace llvm