SnippetGenerator.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 Twine &S)
  29. : StringError(S, inconvertibleErrorCode()) {}
  30. SnippetGenerator::SnippetGenerator(const LLVMState &State, const Options &Opts)
  31. : State(State), Opts(Opts) {}
  32. SnippetGenerator::~SnippetGenerator() = default;
  33. Error SnippetGenerator::generateConfigurations(
  34. const InstructionTemplate &Variant, std::vector<BenchmarkCode> &Benchmarks,
  35. const BitVector &ExtraForbiddenRegs) const {
  36. 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 (Variant.getInstr().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 : Variant.getInstr().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(Variant, ForbiddenRegs)) {
  60. MutableArrayRef<CodeTemplate> Templates = E.get();
  61. // Avoid reallocations in the loop.
  62. Benchmarks.reserve(Benchmarks.size() + Templates.size());
  63. for (CodeTemplate &CT : Templates) {
  64. // TODO: Generate as many BenchmarkCode as needed.
  65. {
  66. BenchmarkCode BC;
  67. BC.Info = CT.Info;
  68. for (InstructionTemplate &IT : CT.Instructions) {
  69. if (auto error = randomizeUnsetVariables(State, ForbiddenRegs, IT))
  70. return error;
  71. BC.Key.Instructions.push_back(IT.build());
  72. }
  73. if (CT.ScratchSpacePointerInReg)
  74. BC.LiveIns.push_back(CT.ScratchSpacePointerInReg);
  75. BC.Key.RegisterInitialValues =
  76. computeRegisterInitialValues(CT.Instructions);
  77. BC.Key.Config = CT.Config;
  78. Benchmarks.emplace_back(std::move(BC));
  79. if (Benchmarks.size() >= Opts.MaxConfigsPerOpcode) {
  80. // We reached the number of allowed configs and return early.
  81. return Error::success();
  82. }
  83. }
  84. }
  85. return Error::success();
  86. } else
  87. return E.takeError();
  88. }
  89. std::vector<RegisterValue> SnippetGenerator::computeRegisterInitialValues(
  90. const std::vector<InstructionTemplate> &Instructions) const {
  91. // Collect all register uses and create an assignment for each of them.
  92. // Ignore memory operands which are handled separately.
  93. // Loop invariant: DefinedRegs[i] is true iif it has been set at least once
  94. // before the current instruction.
  95. BitVector DefinedRegs = State.getRATC().emptyRegisters();
  96. std::vector<RegisterValue> RIV;
  97. for (const InstructionTemplate &IT : Instructions) {
  98. // Returns the register that this Operand sets or uses, or 0 if this is not
  99. // a register.
  100. const auto GetOpReg = [&IT](const Operand &Op) -> unsigned {
  101. if (Op.isMemory())
  102. return 0;
  103. if (Op.isImplicitReg())
  104. return Op.getImplicitReg();
  105. if (Op.isExplicit() && IT.getValueFor(Op).isReg())
  106. return IT.getValueFor(Op).getReg();
  107. return 0;
  108. };
  109. // Collect used registers that have never been def'ed.
  110. for (const Operand &Op : IT.getInstr().Operands) {
  111. if (Op.isUse()) {
  112. const unsigned Reg = GetOpReg(Op);
  113. if (Reg > 0 && !DefinedRegs.test(Reg)) {
  114. RIV.push_back(RegisterValue::zero(Reg));
  115. DefinedRegs.set(Reg);
  116. }
  117. }
  118. }
  119. // Mark defs as having been def'ed.
  120. for (const Operand &Op : IT.getInstr().Operands) {
  121. if (Op.isDef()) {
  122. const unsigned Reg = GetOpReg(Op);
  123. if (Reg > 0)
  124. DefinedRegs.set(Reg);
  125. }
  126. }
  127. }
  128. return RIV;
  129. }
  130. Expected<std::vector<CodeTemplate>>
  131. generateSelfAliasingCodeTemplates(InstructionTemplate Variant) {
  132. const AliasingConfigurations SelfAliasing(Variant.getInstr(),
  133. Variant.getInstr());
  134. if (SelfAliasing.empty())
  135. return make_error<SnippetGeneratorFailure>("empty self aliasing");
  136. std::vector<CodeTemplate> Result;
  137. Result.emplace_back();
  138. CodeTemplate &CT = Result.back();
  139. if (SelfAliasing.hasImplicitAliasing()) {
  140. CT.Info = "implicit Self cycles, picking random values.";
  141. } else {
  142. CT.Info = "explicit self cycles, selecting one aliasing Conf.";
  143. // This is a self aliasing instruction so defs and uses are from the same
  144. // instance, hence twice Variant in the following call.
  145. setRandomAliasing(SelfAliasing, Variant, Variant);
  146. }
  147. CT.Instructions.push_back(std::move(Variant));
  148. return std::move(Result);
  149. }
  150. Expected<std::vector<CodeTemplate>>
  151. generateUnconstrainedCodeTemplates(const InstructionTemplate &Variant,
  152. StringRef Msg) {
  153. std::vector<CodeTemplate> Result;
  154. Result.emplace_back();
  155. CodeTemplate &CT = Result.back();
  156. CT.Info =
  157. std::string(formatv("{0}, repeating an unconstrained assignment", Msg));
  158. CT.Instructions.push_back(std::move(Variant));
  159. return std::move(Result);
  160. }
  161. std::mt19937 &randomGenerator() {
  162. static std::random_device RandomDevice;
  163. static std::mt19937 RandomGenerator(RandomDevice());
  164. return RandomGenerator;
  165. }
  166. size_t randomIndex(size_t Max) {
  167. std::uniform_int_distribution<> Distribution(0, Max);
  168. return Distribution(randomGenerator());
  169. }
  170. template <typename C> static decltype(auto) randomElement(const C &Container) {
  171. assert(!Container.empty() &&
  172. "Can't pick a random element from an empty container)");
  173. return Container[randomIndex(Container.size() - 1)];
  174. }
  175. static void setRegisterOperandValue(const RegisterOperandAssignment &ROV,
  176. InstructionTemplate &IB) {
  177. assert(ROV.Op);
  178. if (ROV.Op->isExplicit()) {
  179. auto &AssignedValue = IB.getValueFor(*ROV.Op);
  180. if (AssignedValue.isValid()) {
  181. assert(AssignedValue.isReg() && AssignedValue.getReg() == ROV.Reg);
  182. return;
  183. }
  184. AssignedValue = MCOperand::createReg(ROV.Reg);
  185. } else {
  186. assert(ROV.Op->isImplicitReg());
  187. assert(ROV.Reg == ROV.Op->getImplicitReg());
  188. }
  189. }
  190. size_t randomBit(const BitVector &Vector) {
  191. assert(Vector.any());
  192. auto Itr = Vector.set_bits_begin();
  193. for (size_t I = randomIndex(Vector.count() - 1); I != 0; --I)
  194. ++Itr;
  195. return *Itr;
  196. }
  197. void setRandomAliasing(const AliasingConfigurations &AliasingConfigurations,
  198. InstructionTemplate &DefIB, InstructionTemplate &UseIB) {
  199. assert(!AliasingConfigurations.empty());
  200. assert(!AliasingConfigurations.hasImplicitAliasing());
  201. const auto &RandomConf = randomElement(AliasingConfigurations.Configurations);
  202. setRegisterOperandValue(randomElement(RandomConf.Defs), DefIB);
  203. setRegisterOperandValue(randomElement(RandomConf.Uses), UseIB);
  204. }
  205. static Error randomizeMCOperand(const LLVMState &State,
  206. const Instruction &Instr, const Variable &Var,
  207. MCOperand &AssignedValue,
  208. const BitVector &ForbiddenRegs) {
  209. const Operand &Op = Instr.getPrimaryOperand(Var);
  210. if (Op.getExplicitOperandInfo().OperandType >=
  211. MCOI::OperandType::OPERAND_FIRST_TARGET)
  212. return State.getExegesisTarget().randomizeTargetMCOperand(
  213. Instr, Var, AssignedValue, ForbiddenRegs);
  214. switch (Op.getExplicitOperandInfo().OperandType) {
  215. case MCOI::OperandType::OPERAND_IMMEDIATE:
  216. // FIXME: explore immediate values too.
  217. AssignedValue = MCOperand::createImm(1);
  218. break;
  219. case MCOI::OperandType::OPERAND_REGISTER: {
  220. assert(Op.isReg());
  221. auto AllowedRegs = Op.getRegisterAliasing().sourceBits();
  222. assert(AllowedRegs.size() == ForbiddenRegs.size());
  223. for (auto I : ForbiddenRegs.set_bits())
  224. AllowedRegs.reset(I);
  225. if (!AllowedRegs.any())
  226. return make_error<Failure>(
  227. Twine("no available registers:\ncandidates:\n")
  228. .concat(debugString(State.getRegInfo(),
  229. Op.getRegisterAliasing().sourceBits()))
  230. .concat("\nforbidden:\n")
  231. .concat(debugString(State.getRegInfo(), ForbiddenRegs)));
  232. AssignedValue = MCOperand::createReg(randomBit(AllowedRegs));
  233. break;
  234. }
  235. default:
  236. break;
  237. }
  238. return Error::success();
  239. }
  240. Error randomizeUnsetVariables(const LLVMState &State,
  241. const BitVector &ForbiddenRegs,
  242. InstructionTemplate &IT) {
  243. for (const Variable &Var : IT.getInstr().Variables) {
  244. MCOperand &AssignedValue = IT.getValueFor(Var);
  245. if (!AssignedValue.isValid())
  246. if (auto Err = randomizeMCOperand(State, IT.getInstr(), Var,
  247. AssignedValue, ForbiddenRegs))
  248. return Err;
  249. }
  250. return Error::success();
  251. }
  252. } // namespace exegesis
  253. } // namespace llvm