emit_glsl.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 "shader_recompiler/backend/glsl/emit_context.h"
  7. #include "shader_recompiler/backend/glsl/emit_glsl.h"
  8. #include "shader_recompiler/backend/glsl/emit_glsl_instructions.h"
  9. #include "shader_recompiler/frontend/ir/ir_emitter.h"
  10. namespace Shader::Backend::GLSL {
  11. namespace {
  12. template <class Func>
  13. struct FuncTraits {};
  14. template <class ReturnType_, class... Args>
  15. struct FuncTraits<ReturnType_ (*)(Args...)> {
  16. using ReturnType = ReturnType_;
  17. static constexpr size_t NUM_ARGS = sizeof...(Args);
  18. template <size_t I>
  19. using ArgType = std::tuple_element_t<I, std::tuple<Args...>>;
  20. };
  21. template <auto func, typename... Args>
  22. void SetDefinition(EmitContext& ctx, IR::Inst* inst, Args... args) {
  23. inst->SetDefinition<Id>(func(ctx, std::forward<Args>(args)...));
  24. }
  25. template <typename ArgType>
  26. auto Arg(EmitContext& ctx, const IR::Value& arg) {
  27. if constexpr (std::is_same_v<ArgType, std::string_view>) {
  28. return ctx.var_alloc.Consume(arg);
  29. } else if constexpr (std::is_same_v<ArgType, const IR::Value&>) {
  30. return arg;
  31. } else if constexpr (std::is_same_v<ArgType, u32>) {
  32. return arg.U32();
  33. } else if constexpr (std::is_same_v<ArgType, IR::Attribute>) {
  34. return arg.Attribute();
  35. } else if constexpr (std::is_same_v<ArgType, IR::Patch>) {
  36. return arg.Patch();
  37. } else if constexpr (std::is_same_v<ArgType, IR::Reg>) {
  38. return arg.Reg();
  39. }
  40. }
  41. template <auto func, bool is_first_arg_inst, size_t... I>
  42. void Invoke(EmitContext& ctx, IR::Inst* inst, std::index_sequence<I...>) {
  43. using Traits = FuncTraits<decltype(func)>;
  44. if constexpr (std::is_same_v<typename Traits::ReturnType, Id>) {
  45. if constexpr (is_first_arg_inst) {
  46. SetDefinition<func>(
  47. ctx, inst, *inst,
  48. Arg<typename Traits::template ArgType<I + 2>>(ctx, inst->Arg(I))...);
  49. } else {
  50. SetDefinition<func>(
  51. ctx, inst, Arg<typename Traits::template ArgType<I + 1>>(ctx, inst->Arg(I))...);
  52. }
  53. } else {
  54. if constexpr (is_first_arg_inst) {
  55. func(ctx, *inst, Arg<typename Traits::template ArgType<I + 2>>(ctx, inst->Arg(I))...);
  56. } else {
  57. func(ctx, Arg<typename Traits::template ArgType<I + 1>>(ctx, inst->Arg(I))...);
  58. }
  59. }
  60. }
  61. template <auto func>
  62. void Invoke(EmitContext& ctx, IR::Inst* inst) {
  63. using Traits = FuncTraits<decltype(func)>;
  64. static_assert(Traits::NUM_ARGS >= 1, "Insufficient arguments");
  65. if constexpr (Traits::NUM_ARGS == 1) {
  66. Invoke<func, false>(ctx, inst, std::make_index_sequence<0>{});
  67. } else {
  68. using FirstArgType = typename Traits::template ArgType<1>;
  69. static constexpr bool is_first_arg_inst = std::is_same_v<FirstArgType, IR::Inst&>;
  70. using Indices = std::make_index_sequence<Traits::NUM_ARGS - (is_first_arg_inst ? 2 : 1)>;
  71. Invoke<func, is_first_arg_inst>(ctx, inst, Indices{});
  72. }
  73. }
  74. void EmitInst(EmitContext& ctx, IR::Inst* inst) {
  75. // ctx.Add("/* $ {} $ */", inst->GetOpcode());
  76. switch (inst->GetOpcode()) {
  77. #define OPCODE(name, result_type, ...) \
  78. case IR::Opcode::name: \
  79. return Invoke<&Emit##name>(ctx, inst);
  80. #include "shader_recompiler/frontend/ir/opcodes.inc"
  81. #undef OPCODE
  82. }
  83. throw LogicError("Invalid opcode {}", inst->GetOpcode());
  84. }
  85. bool IsReference(IR::Inst& inst) {
  86. return inst.GetOpcode() == IR::Opcode::Reference;
  87. }
  88. void PrecolorInst(IR::Inst& phi) {
  89. // Insert phi moves before references to avoid overwritting other phis
  90. const size_t num_args{phi.NumArgs()};
  91. for (size_t i = 0; i < num_args; ++i) {
  92. IR::Block& phi_block{*phi.PhiBlock(i)};
  93. auto it{std::find_if_not(phi_block.rbegin(), phi_block.rend(), IsReference).base()};
  94. IR::IREmitter ir{phi_block, it};
  95. const IR::Value arg{phi.Arg(i)};
  96. if (arg.IsImmediate()) {
  97. ir.PhiMove(phi, arg);
  98. } else {
  99. ir.PhiMove(phi, IR::Value{arg.InstRecursive()});
  100. }
  101. }
  102. for (size_t i = 0; i < num_args; ++i) {
  103. IR::IREmitter{*phi.PhiBlock(i)}.Reference(IR::Value{&phi});
  104. }
  105. }
  106. void Precolor(const IR::Program& program) {
  107. for (IR::Block* const block : program.blocks) {
  108. for (IR::Inst& phi : block->Instructions() | std::views::take_while(IR::IsPhi)) {
  109. PrecolorInst(phi);
  110. }
  111. }
  112. }
  113. void EmitCode(EmitContext& ctx, const IR::Program& program) {
  114. for (const IR::AbstractSyntaxNode& node : program.syntax_list) {
  115. switch (node.type) {
  116. case IR::AbstractSyntaxNode::Type::Block:
  117. for (IR::Inst& inst : node.data.block->Instructions()) {
  118. EmitInst(ctx, &inst);
  119. }
  120. break;
  121. case IR::AbstractSyntaxNode::Type::If:
  122. ctx.Add("if ({}){{", ctx.var_alloc.Consume(node.data.if_node.cond));
  123. break;
  124. case IR::AbstractSyntaxNode::Type::EndIf:
  125. ctx.Add("}}");
  126. break;
  127. case IR::AbstractSyntaxNode::Type::Break:
  128. if (node.data.break_node.cond.IsImmediate()) {
  129. if (node.data.break_node.cond.U1()) {
  130. ctx.Add("break;");
  131. }
  132. } else {
  133. ctx.Add("if({}){{break;}}", ctx.var_alloc.Consume(node.data.break_node.cond));
  134. }
  135. break;
  136. case IR::AbstractSyntaxNode::Type::Return:
  137. case IR::AbstractSyntaxNode::Type::Unreachable:
  138. ctx.Add("return;");
  139. break;
  140. case IR::AbstractSyntaxNode::Type::Loop:
  141. ctx.Add("for(;;){{");
  142. break;
  143. case IR::AbstractSyntaxNode::Type::Repeat:
  144. ctx.Add("if({}){{", ctx.var_alloc.Consume(node.data.repeat.cond));
  145. ctx.Add("continue;\n}}else{{");
  146. ctx.Add("break;\n}}\n}}");
  147. break;
  148. default:
  149. fmt::print("{}", node.type);
  150. throw NotImplementedException("AbstractSyntaxNode::Type {}", node.type);
  151. break;
  152. }
  153. }
  154. }
  155. std::string GlslVersionSpecifier(const EmitContext& ctx) {
  156. if (ctx.uses_y_direction) {
  157. return " compatibility";
  158. }
  159. return "";
  160. }
  161. void DefineVariables(const EmitContext& ctx, std::string& header) {
  162. for (u32 i = 0; i < static_cast<u32>(GlslVarType::Void); ++i) {
  163. const auto type{static_cast<GlslVarType>(i)};
  164. const auto& tracker{ctx.var_alloc.GetUseTracker(type)};
  165. const auto type_name{ctx.var_alloc.GetGlslType(type)};
  166. // Temps/return types that are never used are stored at index 0
  167. if (tracker.uses_temp) {
  168. header += fmt::format("{}{}={}(0);", type_name, ctx.var_alloc.Representation(0, type),
  169. type_name);
  170. }
  171. for (u32 index = 1; index <= tracker.num_used; ++index) {
  172. header += fmt::format("{}{}={}(0);", type_name,
  173. ctx.var_alloc.Representation(index, type), type_name);
  174. }
  175. }
  176. }
  177. } // Anonymous namespace
  178. std::string EmitGLSL(const Profile& profile, const RuntimeInfo& runtime_info, IR::Program& program,
  179. Bindings& bindings) {
  180. EmitContext ctx{program, bindings, profile, runtime_info};
  181. Precolor(program);
  182. EmitCode(ctx, program);
  183. const std::string version{fmt::format("#version 450{}\n", GlslVersionSpecifier(ctx))};
  184. ctx.header.insert(0, version);
  185. if (program.local_memory_size > 0) {
  186. ctx.header += fmt::format("uint lmem[{}];", program.local_memory_size / 4);
  187. }
  188. if (program.shared_memory_size > 0) {
  189. ctx.header += fmt::format("shared uint smem[{}];", program.shared_memory_size / 4);
  190. }
  191. ctx.header += "void main(){\n";
  192. if (program.stage == Stage::VertexA || program.stage == Stage::VertexB) {
  193. ctx.header += "gl_Position = vec4(0.0f, 0.0f, 0.0f, 1.0f);";
  194. // TODO: Properly resolve attribute issues
  195. for (size_t index = 0; index < program.info.stores_generics.size() / 2; ++index) {
  196. if (!program.info.stores_generics[index]) {
  197. ctx.header += fmt::format("out_attr{}=vec4(0,0,0,1);", index);
  198. }
  199. }
  200. }
  201. DefineVariables(ctx, ctx.header);
  202. if (ctx.uses_cc_carry) {
  203. ctx.header += "uint carry;";
  204. }
  205. if (program.info.uses_subgroup_shuffles) {
  206. ctx.header += "bool shfl_in_bounds;";
  207. }
  208. ctx.header += "\n";
  209. ctx.code.insert(0, ctx.header);
  210. ctx.code += "}";
  211. // fmt::print("\n{}\n", ctx.code);
  212. return ctx.code;
  213. }
  214. } // namespace Shader::Backend::GLSL