LightProgramGenerator.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*
  2. Copyright (c) 2019 tevador
  3. This file is part of RandomX.
  4. RandomX is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. RandomX is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with RandomX. If not, see<http://www.gnu.org/licenses/>.
  14. */
  15. #include "blake2/blake2.h"
  16. #include "configuration.h"
  17. #include "Program.hpp"
  18. #include "blake2/endian.h";
  19. #include <iostream>
  20. namespace RandomX {
  21. namespace LightInstruction {
  22. constexpr int IADD_R = 0;
  23. constexpr int IADD_RC = 1;
  24. constexpr int ISUB_R = 2;
  25. constexpr int IMUL_9C = 3;
  26. constexpr int IMUL_R = 4;
  27. constexpr int IMULH_R = 5;
  28. constexpr int ISMULH_R = 6;
  29. constexpr int IMUL_RCP = 7;
  30. constexpr int IXOR_R = 8;
  31. constexpr int IROR_R = 9;
  32. constexpr int COND_R = 10;
  33. constexpr int COUNT = 11;
  34. }
  35. const int lightInstruction[] = {
  36. LightInstruction::IADD_RC,
  37. LightInstruction::IADD_RC,
  38. LightInstruction::ISUB_R,
  39. LightInstruction::ISUB_R,
  40. LightInstruction::IMUL_9C,
  41. LightInstruction::IMUL_R,
  42. LightInstruction::IMUL_R,
  43. LightInstruction::IMUL_R,
  44. LightInstruction::IMULH_R,
  45. LightInstruction::ISMULH_R,
  46. LightInstruction::IMUL_RCP,
  47. LightInstruction::IXOR_R,
  48. LightInstruction::IXOR_R,
  49. LightInstruction::IROR_R,
  50. LightInstruction::IROR_R,
  51. LightInstruction::COND_R
  52. };
  53. namespace LightInstructionOpcode {
  54. constexpr int IADD_R = 0;
  55. constexpr int IADD_RC = RANDOMX_FREQ_IADD_R + RANDOMX_FREQ_IADD_M;
  56. constexpr int ISUB_R = IADD_RC + RANDOMX_FREQ_IADD_RC;
  57. constexpr int IMUL_9C = ISUB_R + RANDOMX_FREQ_ISUB_R + RANDOMX_FREQ_ISUB_M;
  58. constexpr int IMUL_R = IMUL_9C + RANDOMX_FREQ_IMUL_9C;
  59. constexpr int IMULH_R = IMUL_R + RANDOMX_FREQ_IMUL_R + RANDOMX_FREQ_IMUL_M;
  60. constexpr int ISMULH_R = IMULH_R + RANDOMX_FREQ_IMULH_R + RANDOMX_FREQ_IMULH_M;
  61. constexpr int IMUL_RCP = ISMULH_R + RANDOMX_FREQ_ISMULH_R + RANDOMX_FREQ_ISMULH_M;;
  62. constexpr int IXOR_R = IMUL_RCP + RANDOMX_FREQ_IMUL_RCP + RANDOMX_FREQ_INEG_R;
  63. constexpr int IROR_R = IXOR_R + RANDOMX_FREQ_IXOR_R + RANDOMX_FREQ_IXOR_M;
  64. constexpr int COND_R = IROR_R + RANDOMX_FREQ_IROR_R + RANDOMX_FREQ_IROL_R + RANDOMX_FREQ_ISWAP_R + RANDOMX_FREQ_FSWAP_R + RANDOMX_FREQ_FADD_R + RANDOMX_FREQ_FADD_M + RANDOMX_FREQ_FSUB_R + RANDOMX_FREQ_FSUB_M + RANDOMX_FREQ_FSCAL_R + RANDOMX_FREQ_FMUL_R + RANDOMX_FREQ_FDIV_M + RANDOMX_FREQ_FSQRT_R;
  65. }
  66. const int lightInstructionOpcode[] = {
  67. LightInstructionOpcode::IADD_R,
  68. LightInstructionOpcode::IADD_RC,
  69. LightInstructionOpcode::ISUB_R,
  70. LightInstructionOpcode::IMUL_9C,
  71. LightInstructionOpcode::IMUL_R,
  72. LightInstructionOpcode::IMULH_R,
  73. LightInstructionOpcode::ISMULH_R,
  74. LightInstructionOpcode::IMUL_RCP,
  75. LightInstructionOpcode::IXOR_R,
  76. LightInstructionOpcode::IROR_R,
  77. LightInstructionOpcode::COND_R
  78. };
  79. constexpr int ALU_COUNT_MUL = 1;
  80. constexpr int ALU_COUNT = 4;
  81. constexpr int LIGHT_OPCODE_BITS = 4;
  82. constexpr int V4_SRC_INDEX_BITS = 3;
  83. constexpr int V4_DST_INDEX_BITS = 3;
  84. static int blakeCounter = 0;
  85. // If we don't have enough data available, generate more
  86. static FORCE_INLINE void check_data(size_t& data_index, const size_t bytes_needed, uint8_t* data, const size_t data_size)
  87. {
  88. if (data_index + bytes_needed > data_size)
  89. {
  90. std::cout << "Calling Blake " << (++blakeCounter) << std::endl;
  91. blake2b(data, data_size, data, data_size, nullptr, 0);
  92. data_index = 0;
  93. }
  94. }
  95. void generateLightProgram(LightProgram& prog, const void* seed, int indexRegister) {
  96. // Source: https://www.agner.org/optimize/instruction_tables.pdf
  97. const int op_latency[LightInstruction::COUNT] = { 1, 2, 1, 2, 3, 5, 5, 4, 1, 2, 5 };
  98. // Instruction latencies for theoretical ASIC implementation
  99. const int asic_op_latency[LightInstruction::COUNT] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
  100. // Available ALUs for each instruction
  101. const int op_ALUs[LightInstruction::COUNT] = { ALU_COUNT, ALU_COUNT, ALU_COUNT, ALU_COUNT, ALU_COUNT_MUL, ALU_COUNT_MUL, ALU_COUNT_MUL, ALU_COUNT_MUL, ALU_COUNT, ALU_COUNT, ALU_COUNT };
  102. uint8_t data[64];
  103. memset(data, 0, sizeof(data));
  104. memcpy(data, seed, SeedSize);
  105. // Set data_index past the last byte in data
  106. // to trigger full data update with blake hash
  107. // before we start using it
  108. size_t data_index = sizeof(data);
  109. int code_size;
  110. do {
  111. uint8_t opcode;
  112. uint8_t dst_index;
  113. uint8_t src_index;
  114. uint32_t imm32 = 0;
  115. int latency[8];
  116. int asic_latency[9];
  117. // Tracks previous instruction and value of the source operand for registers R0-R3 throughout code execution
  118. // byte 0: current value of the destination register
  119. // byte 1: instruction opcode
  120. // byte 2: current value of the source register
  121. //
  122. // Registers R4-R8 are constant and are treated as having the same value because when we do
  123. // the same operation twice with two constant source registers, it can be optimized into a single operation
  124. uint64_t inst_data[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
  125. bool alu_busy[RANDOMX_LPROG_LATENCY + 1][ALU_COUNT];
  126. bool is_rotation[LightInstruction::COUNT];
  127. bool rotated[8];
  128. int rotate_count = 0;
  129. memset(latency, 0, sizeof(latency));
  130. memset(asic_latency, 0, sizeof(asic_latency));
  131. memset(alu_busy, 0, sizeof(alu_busy));
  132. memset(is_rotation, 0, sizeof(is_rotation));
  133. memset(rotated, 0, sizeof(rotated));
  134. is_rotation[LightInstruction::IROR_R] = true;
  135. int num_retries = 0;
  136. code_size = 0;
  137. int total_iterations = 0;
  138. // Generate random code to achieve minimal required latency for our abstract CPU
  139. // Try to get this latency for all 4 registers
  140. while (((latency[0] < RANDOMX_LPROG_LATENCY) || (latency[1] < RANDOMX_LPROG_LATENCY) || (latency[2] < RANDOMX_LPROG_LATENCY) || (latency[3] < RANDOMX_LPROG_LATENCY)
  141. || (latency[4] < RANDOMX_LPROG_LATENCY) || (latency[5] < RANDOMX_LPROG_LATENCY) || (latency[6] < RANDOMX_LPROG_LATENCY) || (latency[7] < RANDOMX_LPROG_LATENCY)) && (num_retries < 64))
  142. {
  143. // Fail-safe to guarantee loop termination
  144. ++total_iterations;
  145. if (total_iterations > 1024) {
  146. std::cout << "total_iterations = " << total_iterations << std::endl;
  147. break;
  148. }
  149. check_data(data_index, 1, data, sizeof(data));
  150. const uint8_t b1 = data[data_index++];
  151. int instrType = lightInstruction[b1 & ((1 << LIGHT_OPCODE_BITS) - 1)];
  152. check_data(data_index, 1, data, sizeof(data));
  153. const uint8_t b2 = data[data_index++];
  154. dst_index = b2 & ((1 << V4_DST_INDEX_BITS) - 1);
  155. src_index = (b2 >> (V4_DST_INDEX_BITS)) & ((1 << V4_SRC_INDEX_BITS) - 1);
  156. const int a = dst_index;
  157. int b = src_index;
  158. // Don't do rotation with the same destination twice because it's equal to a single rotation
  159. if (is_rotation[instrType] && rotated[a])
  160. {
  161. continue;
  162. }
  163. // Don't do the same instruction (except MUL) with the same source value twice because all other cases can be optimized:
  164. // 2x IADD_RC(a, b, C) = IADD_RC(a, b*2, C1+C2)
  165. // 2x ISUB_R(a, b) = ISUB_R(a, 2*b)
  166. // 2x IMUL_R(a, b) = IMUL_R(a, b*b)
  167. // 2x IMUL_9C(a, C) = 9 * (9 * a + C1) + C2 = 81 * a + (9 * C1 + C2)
  168. // 2x IMUL_RCP(a, C) = a * (C * C)
  169. // 2x IXOR_R = NOP
  170. // 2x IROR_R(a, b) = IROR_R(a, 2*b)
  171. if (instrType != LightInstruction::IMULH_R && instrType != LightInstruction::ISMULH_R && ((inst_data[a] & 0xFFFF00) == (instrType << 8) + ((inst_data[b] & 255) << 16)))
  172. {
  173. continue;
  174. }
  175. if ((instrType == LightInstruction::IADD_RC) || (instrType == LightInstruction::IMUL_9C) || (instrType == LightInstruction::IMUL_RCP) || (instrType == LightInstruction::COND_R) || ((instrType != LightInstruction::IMULH_R) && (instrType != LightInstruction::ISMULH_R) && (a == b)))
  176. {
  177. check_data(data_index, 4, data, sizeof(data));
  178. imm32 = load32(&data[data_index++]);
  179. }
  180. // Find which ALU is available (and when) for this instruction
  181. int next_latency = (latency[a] > latency[b]) ? latency[a] : latency[b];
  182. int alu_index = -1;
  183. while (next_latency < RANDOMX_LPROG_LATENCY)
  184. {
  185. for (int i = op_ALUs[instrType] - 1; i >= 0; --i)
  186. {
  187. if (!alu_busy[next_latency][i])
  188. {
  189. // ADD is implemented as two 1-cycle instructions on a real CPU, so do an additional availability check
  190. if ((instrType == LightInstruction::IADD_RC || instrType == LightInstruction::IMUL_9C || instrType == LightInstruction::IMULH_R || instrType == LightInstruction::ISMULH_R) && alu_busy[next_latency + 1][i])
  191. {
  192. continue;
  193. }
  194. // Rotation can only start when previous rotation is finished, so do an additional availability check
  195. if (is_rotation[instrType] && (next_latency < rotate_count * op_latency[instrType]))
  196. {
  197. continue;
  198. }
  199. alu_index = i;
  200. break;
  201. }
  202. }
  203. if (alu_index >= 0)
  204. {
  205. break;
  206. }
  207. ++next_latency;
  208. }
  209. // Don't generate instructions that leave some register unchanged for more than 15 cycles
  210. if (next_latency > latency[a] + 15)
  211. {
  212. continue;
  213. }
  214. next_latency += op_latency[instrType];
  215. if (next_latency <= RANDOMX_LPROG_LATENCY)
  216. {
  217. if (is_rotation[instrType])
  218. {
  219. ++rotate_count;
  220. }
  221. // Mark ALU as busy only for the first cycle when it starts executing the instruction because ALUs are fully pipelined
  222. alu_busy[next_latency - op_latency[instrType]][alu_index] = true;
  223. latency[a] = next_latency;
  224. // ASIC is supposed to have enough ALUs to run as many independent instructions per cycle as possible, so latency calculation for ASIC is simple
  225. asic_latency[a] = ((asic_latency[a] > asic_latency[b]) ? asic_latency[a] : asic_latency[b]) + asic_op_latency[instrType];
  226. rotated[a] = is_rotation[instrType];
  227. inst_data[a] = code_size + (instrType << 8) + ((inst_data[b] & 255) << 16);
  228. prog(code_size).opcode = lightInstructionOpcode[instrType];
  229. prog(code_size).dst = dst_index;
  230. prog(code_size).src = src_index;
  231. prog(code_size).setImm32(imm32);
  232. if (instrType == LightInstruction::IADD_RC || instrType == LightInstruction::IMUL_9C || instrType == LightInstruction::IMULH_R || instrType == LightInstruction::ISMULH_R)
  233. {
  234. // ADD instruction is implemented as two 1-cycle instructions on a real CPU, so mark ALU as busy for the next cycle too
  235. alu_busy[next_latency - op_latency[instrType] + 1][alu_index] = true;
  236. }
  237. ++code_size;
  238. if (code_size >= RANDOMX_LPROG_MIN_SIZE)
  239. {
  240. break;
  241. }
  242. }
  243. else
  244. {
  245. ++num_retries;
  246. std::cout << "Retry " << num_retries << " with code_size = " << code_size << ", next_latency = " << next_latency << std::endl;
  247. }
  248. }
  249. // ASIC has more execution resources and can extract as much parallelism from the code as possible
  250. // We need to add a few more MUL and ROR instructions to achieve minimal required latency for ASIC
  251. // Get this latency for at least 1 of the 4 registers
  252. const int prev_code_size = code_size;
  253. if ((code_size < RANDOMX_LPROG_MAX_SIZE) && (asic_latency[indexRegister] < RANDOMX_LPROG_ASIC_LATENCY))
  254. {
  255. int min_idx = indexRegister;
  256. int max_idx = 0;
  257. for (int i = 1; i < 8; ++i)
  258. {
  259. //if (asic_latency[i] < asic_latency[min_idx]) min_idx = i;
  260. if (asic_latency[i] > asic_latency[max_idx]) max_idx = i;
  261. }
  262. const int pattern[3] = { LightInstruction::IMUL_R, LightInstruction::IROR_R, LightInstruction::IMUL_R };
  263. const int instrType = pattern[(code_size - prev_code_size) % 3];
  264. latency[min_idx] = latency[max_idx] + op_latency[instrType];
  265. asic_latency[min_idx] = asic_latency[max_idx] + asic_op_latency[instrType];
  266. prog(code_size).opcode = lightInstructionOpcode[instrType];
  267. prog(code_size).dst = min_idx;
  268. prog(code_size).src = max_idx;
  269. ++code_size;
  270. }
  271. for (int i = 0; i < 8; ++i) {
  272. std::cout << "Latency " << i << " = " << latency[i] << std::endl;
  273. }
  274. std::cout << "Code size = " << code_size << std::endl;
  275. std::cout << "ALUs:" << std::endl;
  276. for (int i = 0; i < RANDOMX_LPROG_LATENCY + 1; ++i) {
  277. for (int j = 0; j < ALU_COUNT; ++j) {
  278. std::cout << (alu_busy[i][j] ? '*' : '_');
  279. }
  280. std::cout << std::endl;
  281. }
  282. // There is ~98.15% chance that loop condition is false, so this loop will execute only 1 iteration most of the time
  283. // It never does more than 4 iterations for all block heights < 10,000,000
  284. } while ((code_size < RANDOMX_LPROG_MIN_SIZE) || (code_size > RANDOMX_LPROG_MAX_SIZE));
  285. prog.setSize(code_size);
  286. }
  287. }