emit_glasm.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <ranges>
  5. #include <string>
  6. #include <tuple>
  7. #include "shader_recompiler/backend/bindings.h"
  8. #include "shader_recompiler/backend/glasm/emit_context.h"
  9. #include "shader_recompiler/backend/glasm/emit_glasm.h"
  10. #include "shader_recompiler/backend/glasm/emit_glasm_instructions.h"
  11. #include "shader_recompiler/frontend/ir/ir_emitter.h"
  12. #include "shader_recompiler/frontend/ir/program.h"
  13. #include "shader_recompiler/profile.h"
  14. namespace Shader::Backend::GLASM {
  15. namespace {
  16. template <class Func>
  17. struct FuncTraits {};
  18. template <class ReturnType_, class... Args>
  19. struct FuncTraits<ReturnType_ (*)(Args...)> {
  20. using ReturnType = ReturnType_;
  21. static constexpr size_t NUM_ARGS = sizeof...(Args);
  22. template <size_t I>
  23. using ArgType = std::tuple_element_t<I, std::tuple<Args...>>;
  24. };
  25. template <typename T>
  26. struct Identity {
  27. Identity(T data_) : data{data_} {}
  28. T Extract() {
  29. return data;
  30. }
  31. T data;
  32. };
  33. template <bool scalar>
  34. class RegWrapper {
  35. public:
  36. RegWrapper(EmitContext& ctx, const IR::Value& ir_value) : reg_alloc{ctx.reg_alloc} {
  37. const Value value{reg_alloc.Peek(ir_value)};
  38. if (value.type == Type::Register) {
  39. inst = ir_value.InstRecursive();
  40. reg = Register{value};
  41. } else {
  42. const bool is_long{value.type == Type::F64 || value.type == Type::U64};
  43. reg = is_long ? reg_alloc.AllocLongReg() : reg_alloc.AllocReg();
  44. }
  45. switch (value.type) {
  46. case Type::Register:
  47. break;
  48. case Type::U32:
  49. ctx.Add("MOV.U {}.x,{};", reg, value.imm_u32);
  50. break;
  51. case Type::S32:
  52. ctx.Add("MOV.S {}.x,{};", reg, value.imm_s32);
  53. break;
  54. case Type::F32:
  55. ctx.Add("MOV.F {}.x,{};", reg, value.imm_f32);
  56. break;
  57. case Type::U64:
  58. ctx.Add("MOV.U64 {}.x,{};", reg, value.imm_u64);
  59. break;
  60. case Type::F64:
  61. ctx.Add("MOV.F64 {}.x,{};", reg, value.imm_f64);
  62. break;
  63. }
  64. }
  65. auto Extract() {
  66. if (inst) {
  67. reg_alloc.Unref(*inst);
  68. } else {
  69. reg_alloc.FreeReg(reg);
  70. }
  71. return std::conditional_t<scalar, ScalarRegister, Register>{Value{reg}};
  72. }
  73. private:
  74. RegAlloc& reg_alloc;
  75. IR::Inst* inst{};
  76. Register reg{};
  77. };
  78. template <typename ArgType>
  79. class ValueWrapper {
  80. public:
  81. ValueWrapper(EmitContext& ctx, const IR::Value& ir_value_)
  82. : reg_alloc{ctx.reg_alloc}, ir_value{ir_value_}, value{reg_alloc.Peek(ir_value)} {}
  83. ArgType Extract() {
  84. if (!ir_value.IsImmediate()) {
  85. reg_alloc.Unref(*ir_value.InstRecursive());
  86. }
  87. return value;
  88. }
  89. private:
  90. RegAlloc& reg_alloc;
  91. const IR::Value& ir_value;
  92. ArgType value;
  93. };
  94. template <typename ArgType>
  95. auto Arg(EmitContext& ctx, const IR::Value& arg) {
  96. if constexpr (std::is_same_v<ArgType, Register>) {
  97. return RegWrapper<false>{ctx, arg};
  98. } else if constexpr (std::is_same_v<ArgType, ScalarRegister>) {
  99. return RegWrapper<true>{ctx, arg};
  100. } else if constexpr (std::is_base_of_v<Value, ArgType>) {
  101. return ValueWrapper<ArgType>{ctx, arg};
  102. } else if constexpr (std::is_same_v<ArgType, const IR::Value&>) {
  103. return Identity<const IR::Value&>{arg};
  104. } else if constexpr (std::is_same_v<ArgType, u32>) {
  105. return Identity{arg.U32()};
  106. } else if constexpr (std::is_same_v<ArgType, IR::Attribute>) {
  107. return Identity{arg.Attribute()};
  108. } else if constexpr (std::is_same_v<ArgType, IR::Patch>) {
  109. return Identity{arg.Patch()};
  110. } else if constexpr (std::is_same_v<ArgType, IR::Reg>) {
  111. return Identity{arg.Reg()};
  112. }
  113. }
  114. template <auto func, bool is_first_arg_inst>
  115. struct InvokeCall {
  116. template <typename... Args>
  117. InvokeCall(EmitContext& ctx, IR::Inst* inst, Args&&... args) {
  118. if constexpr (is_first_arg_inst) {
  119. func(ctx, *inst, args.Extract()...);
  120. } else {
  121. func(ctx, args.Extract()...);
  122. }
  123. }
  124. };
  125. template <auto func, bool is_first_arg_inst, size_t... I>
  126. void Invoke(EmitContext& ctx, IR::Inst* inst, std::index_sequence<I...>) {
  127. using Traits = FuncTraits<decltype(func)>;
  128. if constexpr (is_first_arg_inst) {
  129. InvokeCall<func, is_first_arg_inst>{
  130. ctx, inst, Arg<typename Traits::template ArgType<I + 2>>(ctx, inst->Arg(I))...};
  131. } else {
  132. InvokeCall<func, is_first_arg_inst>{
  133. ctx, inst, Arg<typename Traits::template ArgType<I + 1>>(ctx, inst->Arg(I))...};
  134. }
  135. }
  136. template <auto func>
  137. void Invoke(EmitContext& ctx, IR::Inst* inst) {
  138. using Traits = FuncTraits<decltype(func)>;
  139. static_assert(Traits::NUM_ARGS >= 1, "Insufficient arguments");
  140. if constexpr (Traits::NUM_ARGS == 1) {
  141. Invoke<func, false>(ctx, inst, std::make_index_sequence<0>{});
  142. } else {
  143. using FirstArgType = typename Traits::template ArgType<1>;
  144. static constexpr bool is_first_arg_inst = std::is_same_v<FirstArgType, IR::Inst&>;
  145. using Indices = std::make_index_sequence<Traits::NUM_ARGS - (is_first_arg_inst ? 2 : 1)>;
  146. Invoke<func, is_first_arg_inst>(ctx, inst, Indices{});
  147. }
  148. }
  149. void EmitInst(EmitContext& ctx, IR::Inst* inst) {
  150. switch (inst->GetOpcode()) {
  151. #define OPCODE(name, result_type, ...) \
  152. case IR::Opcode::name: \
  153. return Invoke<&Emit##name>(ctx, inst);
  154. #include "shader_recompiler/frontend/ir/opcodes.inc"
  155. #undef OPCODE
  156. }
  157. throw LogicError("Invalid opcode {}", inst->GetOpcode());
  158. }
  159. void Precolor(EmitContext& ctx, const IR::Program& program) {
  160. for (IR::Block* const block : program.blocks) {
  161. for (IR::Inst& phi : block->Instructions() | std::views::take_while(IR::IsPhi)) {
  162. switch (phi.Arg(0).Type()) {
  163. case IR::Type::U1:
  164. case IR::Type::U32:
  165. case IR::Type::F32:
  166. ctx.reg_alloc.Define(phi);
  167. break;
  168. case IR::Type::U64:
  169. case IR::Type::F64:
  170. ctx.reg_alloc.LongDefine(phi);
  171. break;
  172. default:
  173. throw NotImplementedException("Phi node type {}", phi.Type());
  174. }
  175. const size_t num_args{phi.NumArgs()};
  176. for (size_t i = 0; i < num_args; ++i) {
  177. IR::IREmitter{*phi.PhiBlock(i)}.PhiMove(phi, phi.Arg(i));
  178. }
  179. // Add reference to the phi node on the phi predecessor to avoid overwritting it
  180. for (size_t i = 0; i < num_args; ++i) {
  181. IR::IREmitter{*phi.PhiBlock(i)}.DummyReference(IR::Value{&phi});
  182. }
  183. }
  184. }
  185. }
  186. void EmitCode(EmitContext& ctx, const IR::Program& program) {
  187. const auto eval{
  188. [&](const IR::U1& cond) { return ScalarS32{ctx.reg_alloc.Consume(IR::Value{cond})}; }};
  189. for (const IR::AbstractSyntaxNode& node : program.syntax_list) {
  190. switch (node.type) {
  191. case IR::AbstractSyntaxNode::Type::Block:
  192. for (IR::Inst& inst : node.block->Instructions()) {
  193. EmitInst(ctx, &inst);
  194. }
  195. break;
  196. case IR::AbstractSyntaxNode::Type::If:
  197. ctx.Add("MOV.S.CC RC,{};"
  198. "IF NE.x;",
  199. eval(node.if_node.cond));
  200. break;
  201. case IR::AbstractSyntaxNode::Type::EndIf:
  202. ctx.Add("ENDIF;");
  203. break;
  204. case IR::AbstractSyntaxNode::Type::Loop:
  205. ctx.Add("REP;");
  206. break;
  207. case IR::AbstractSyntaxNode::Type::Repeat:
  208. if (node.repeat.cond.IsImmediate()) {
  209. if (node.repeat.cond.U1()) {
  210. ctx.Add("ENDREP;");
  211. } else {
  212. ctx.Add("BRK;"
  213. "ENDREP;");
  214. }
  215. } else {
  216. ctx.Add("MOV.S.CC RC,{};"
  217. "BRK (EQ.x);"
  218. "ENDREP;",
  219. eval(node.repeat.cond));
  220. }
  221. break;
  222. case IR::AbstractSyntaxNode::Type::Break:
  223. if (node.break_node.cond.IsImmediate()) {
  224. if (node.break_node.cond.U1()) {
  225. ctx.Add("BRK;");
  226. }
  227. } else {
  228. ctx.Add("MOV.S.CC RC,{};"
  229. "BRK (NE.x);",
  230. eval(node.break_node.cond));
  231. }
  232. break;
  233. case IR::AbstractSyntaxNode::Type::Return:
  234. case IR::AbstractSyntaxNode::Type::Unreachable:
  235. ctx.Add("RET;");
  236. break;
  237. }
  238. }
  239. }
  240. void SetupOptions(std::string& header, Info info) {
  241. if (info.uses_int64_bit_atomics) {
  242. header += "OPTION NV_shader_atomic_int64;";
  243. }
  244. if (info.uses_atomic_f32_add) {
  245. header += "OPTION NV_shader_atomic_float;";
  246. }
  247. if (info.uses_atomic_f16x2_add || info.uses_atomic_f16x2_min || info.uses_atomic_f16x2_max) {
  248. header += "OPTION NV_shader_atomic_fp16_vector;";
  249. }
  250. if (info.uses_subgroup_invocation_id || info.uses_subgroup_mask || info.uses_subgroup_vote) {
  251. header += "OPTION NV_shader_thread_group;";
  252. }
  253. if (info.uses_subgroup_shuffles) {
  254. header += "OPTION NV_shader_thread_shuffle;";
  255. }
  256. // TODO: Track the shared atomic ops
  257. header += "OPTION NV_shader_storage_buffer;"
  258. "OPTION NV_gpu_program_fp64;"
  259. "OPTION NV_bindless_texture;";
  260. }
  261. } // Anonymous namespace
  262. std::string EmitGLASM(const Profile&, IR::Program& program, Bindings&) {
  263. EmitContext ctx{program};
  264. Precolor(ctx, program);
  265. EmitCode(ctx, program);
  266. std::string header = "!!NVcp5.0\n"
  267. "OPTION NV_internal;";
  268. SetupOptions(header, program.info);
  269. switch (program.stage) {
  270. case Stage::Compute:
  271. header += fmt::format("GROUP_SIZE {} {} {};", program.workgroup_size[0],
  272. program.workgroup_size[1], program.workgroup_size[2]);
  273. break;
  274. default:
  275. break;
  276. }
  277. if (program.shared_memory_size > 0) {
  278. header += fmt::format("SHARED_MEMORY {};", program.shared_memory_size);
  279. header += fmt::format("SHARED shared_mem[]={{program.sharedmem}};");
  280. }
  281. header += "TEMP ";
  282. for (size_t index = 0; index < ctx.reg_alloc.NumUsedRegisters(); ++index) {
  283. header += fmt::format("R{},", index);
  284. }
  285. header += "RC;"
  286. "LONG TEMP ";
  287. for (size_t index = 0; index < ctx.reg_alloc.NumUsedLongRegisters(); ++index) {
  288. header += fmt::format("D{},", index);
  289. }
  290. header += "DC;";
  291. ctx.code.insert(0, header);
  292. ctx.code += "END";
  293. return ctx.code;
  294. }
  295. } // namespace Shader::Backend::GLASM