shader_environment.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <filesystem>
  5. #include <fstream>
  6. #include <memory>
  7. #include <optional>
  8. #include <utility>
  9. #include "common/assert.h"
  10. #include "common/cityhash.h"
  11. #include "common/common_types.h"
  12. #include "common/div_ceil.h"
  13. #include "common/fs/fs.h"
  14. #include "common/fs/path_util.h"
  15. #include "common/logging/log.h"
  16. #include "common/polyfill_ranges.h"
  17. #include "shader_recompiler/environment.h"
  18. #include "video_core/engines/kepler_compute.h"
  19. #include "video_core/memory_manager.h"
  20. #include "video_core/shader_environment.h"
  21. #include "video_core/texture_cache/format_lookup_table.h"
  22. #include "video_core/textures/texture.h"
  23. namespace VideoCommon {
  24. constexpr std::array<char, 8> MAGIC_NUMBER{'y', 'u', 'z', 'u', 'c', 'a', 'c', 'h'};
  25. constexpr size_t INST_SIZE = sizeof(u64);
  26. using Maxwell = Tegra::Engines::Maxwell3D::Regs;
  27. static u64 MakeCbufKey(u32 index, u32 offset) {
  28. return (static_cast<u64>(index) << 32) | offset;
  29. }
  30. static Shader::TextureType ConvertTextureType(const Tegra::Texture::TICEntry& entry) {
  31. switch (entry.texture_type) {
  32. case Tegra::Texture::TextureType::Texture1D:
  33. return Shader::TextureType::Color1D;
  34. case Tegra::Texture::TextureType::Texture2D:
  35. case Tegra::Texture::TextureType::Texture2DNoMipmap:
  36. return entry.normalized_coords ? Shader::TextureType::Color2D
  37. : Shader::TextureType::Color2DRect;
  38. case Tegra::Texture::TextureType::Texture3D:
  39. return Shader::TextureType::Color3D;
  40. case Tegra::Texture::TextureType::TextureCubemap:
  41. return Shader::TextureType::ColorCube;
  42. case Tegra::Texture::TextureType::Texture1DArray:
  43. return Shader::TextureType::ColorArray1D;
  44. case Tegra::Texture::TextureType::Texture2DArray:
  45. return Shader::TextureType::ColorArray2D;
  46. case Tegra::Texture::TextureType::Texture1DBuffer:
  47. return Shader::TextureType::Buffer;
  48. case Tegra::Texture::TextureType::TextureCubeArray:
  49. return Shader::TextureType::ColorArrayCube;
  50. default:
  51. UNIMPLEMENTED();
  52. return Shader::TextureType::Color2D;
  53. }
  54. }
  55. static Shader::TexturePixelFormat ConvertTexturePixelFormat(const Tegra::Texture::TICEntry& entry) {
  56. switch (PixelFormatFromTextureInfo(entry.format, entry.r_type, entry.g_type, entry.b_type,
  57. entry.a_type, entry.srgb_conversion)) {
  58. case VideoCore::Surface::PixelFormat::A8B8G8R8_SNORM:
  59. return Shader::TexturePixelFormat::A8B8G8R8_SNORM;
  60. case VideoCore::Surface::PixelFormat::R8_SNORM:
  61. return Shader::TexturePixelFormat::R8_SNORM;
  62. case VideoCore::Surface::PixelFormat::R8G8_SNORM:
  63. return Shader::TexturePixelFormat::R8G8_SNORM;
  64. case VideoCore::Surface::PixelFormat::R16G16B16A16_SNORM:
  65. return Shader::TexturePixelFormat::R16G16B16A16_SNORM;
  66. case VideoCore::Surface::PixelFormat::R16G16_SNORM:
  67. return Shader::TexturePixelFormat::R16G16_SNORM;
  68. case VideoCore::Surface::PixelFormat::R16_SNORM:
  69. return Shader::TexturePixelFormat::R16_SNORM;
  70. default:
  71. return Shader::TexturePixelFormat::OTHER;
  72. }
  73. }
  74. static std::string_view StageToPrefix(Shader::Stage stage) {
  75. switch (stage) {
  76. case Shader::Stage::VertexB:
  77. return "VB";
  78. case Shader::Stage::TessellationControl:
  79. return "TC";
  80. case Shader::Stage::TessellationEval:
  81. return "TE";
  82. case Shader::Stage::Geometry:
  83. return "GS";
  84. case Shader::Stage::Fragment:
  85. return "FS";
  86. case Shader::Stage::Compute:
  87. return "CS";
  88. case Shader::Stage::VertexA:
  89. return "VA";
  90. default:
  91. return "UK";
  92. }
  93. }
  94. static void DumpImpl(u64 pipeline_hash, u64 shader_hash, std::span<const u64> code,
  95. [[maybe_unused]] u32 read_highest, [[maybe_unused]] u32 read_lowest,
  96. u32 initial_offset, Shader::Stage stage) {
  97. const auto shader_dir{Common::FS::GetYuzuPath(Common::FS::YuzuPath::DumpDir)};
  98. const auto base_dir{shader_dir / "shaders"};
  99. if (!Common::FS::CreateDir(shader_dir) || !Common::FS::CreateDir(base_dir)) {
  100. LOG_ERROR(Common_Filesystem, "Failed to create shader dump directories");
  101. return;
  102. }
  103. const auto prefix = StageToPrefix(stage);
  104. const auto name{base_dir /
  105. fmt::format("{:016x}_{}_{:016x}.ash", pipeline_hash, prefix, shader_hash)};
  106. std::fstream shader_file(name, std::ios::out | std::ios::binary);
  107. ASSERT(initial_offset % sizeof(u64) == 0);
  108. const size_t jump_index = initial_offset / sizeof(u64);
  109. const size_t code_size = code.size_bytes() - initial_offset;
  110. shader_file.write(reinterpret_cast<const char*>(&code[jump_index]), code_size);
  111. // + 1 instruction, due to the fact that we skip the final self branch instruction in the code,
  112. // but we need to consider it for padding, otherwise nvdisasm rages.
  113. const size_t padding_needed = (32 - ((code_size + INST_SIZE) % 32)) % 32;
  114. for (size_t i = 0; i < INST_SIZE + padding_needed; i++) {
  115. shader_file.put(0);
  116. }
  117. }
  118. GenericEnvironment::GenericEnvironment(Tegra::MemoryManager& gpu_memory_, GPUVAddr program_base_,
  119. u32 start_address_)
  120. : gpu_memory{&gpu_memory_}, program_base{program_base_} {
  121. start_address = start_address_;
  122. }
  123. GenericEnvironment::~GenericEnvironment() = default;
  124. u32 GenericEnvironment::TextureBoundBuffer() const {
  125. return texture_bound;
  126. }
  127. u32 GenericEnvironment::LocalMemorySize() const {
  128. return local_memory_size;
  129. }
  130. u32 GenericEnvironment::SharedMemorySize() const {
  131. return shared_memory_size;
  132. }
  133. std::array<u32, 3> GenericEnvironment::WorkgroupSize() const {
  134. return workgroup_size;
  135. }
  136. u64 GenericEnvironment::ReadInstruction(u32 address) {
  137. read_lowest = std::min(read_lowest, address);
  138. read_highest = std::max(read_highest, address);
  139. if (address >= cached_lowest && address < cached_highest) {
  140. return code[(address - cached_lowest) / INST_SIZE];
  141. }
  142. has_unbound_instructions = true;
  143. return gpu_memory->Read<u64>(program_base + address);
  144. }
  145. std::optional<u64> GenericEnvironment::Analyze() {
  146. const std::optional<u64> size{TryFindSize()};
  147. if (!size) {
  148. return std::nullopt;
  149. }
  150. cached_lowest = start_address;
  151. cached_highest = start_address + static_cast<u32>(*size);
  152. return Common::CityHash64(reinterpret_cast<const char*>(code.data()), *size);
  153. }
  154. void GenericEnvironment::SetCachedSize(size_t size_bytes) {
  155. cached_lowest = start_address;
  156. cached_highest = start_address + static_cast<u32>(size_bytes);
  157. code.resize(CachedSizeWords());
  158. gpu_memory->ReadBlock(program_base + cached_lowest, code.data(), code.size() * sizeof(u64));
  159. }
  160. size_t GenericEnvironment::CachedSizeWords() const noexcept {
  161. return CachedSizeBytes() / INST_SIZE;
  162. }
  163. size_t GenericEnvironment::CachedSizeBytes() const noexcept {
  164. return static_cast<size_t>(cached_highest) - cached_lowest + INST_SIZE;
  165. }
  166. size_t GenericEnvironment::ReadSizeBytes() const noexcept {
  167. return read_highest - read_lowest + INST_SIZE;
  168. }
  169. bool GenericEnvironment::CanBeSerialized() const noexcept {
  170. return !has_unbound_instructions;
  171. }
  172. u64 GenericEnvironment::CalculateHash() const {
  173. const size_t size{ReadSizeBytes()};
  174. const auto data{std::make_unique<char[]>(size)};
  175. gpu_memory->ReadBlock(program_base + read_lowest, data.get(), size);
  176. return Common::CityHash64(data.get(), size);
  177. }
  178. void GenericEnvironment::Dump(u64 pipeline_hash, u64 shader_hash) {
  179. DumpImpl(pipeline_hash, shader_hash, code, read_highest, read_lowest, initial_offset, stage);
  180. }
  181. void GenericEnvironment::Serialize(std::ofstream& file) const {
  182. const u64 code_size{static_cast<u64>(CachedSizeBytes())};
  183. const u64 num_texture_types{static_cast<u64>(texture_types.size())};
  184. const u64 num_texture_pixel_formats{static_cast<u64>(texture_pixel_formats.size())};
  185. const u64 num_cbuf_values{static_cast<u64>(cbuf_values.size())};
  186. const u64 num_cbuf_replacement_values{static_cast<u64>(cbuf_replacements.size())};
  187. file.write(reinterpret_cast<const char*>(&code_size), sizeof(code_size))
  188. .write(reinterpret_cast<const char*>(&num_texture_types), sizeof(num_texture_types))
  189. .write(reinterpret_cast<const char*>(&num_texture_pixel_formats),
  190. sizeof(num_texture_pixel_formats))
  191. .write(reinterpret_cast<const char*>(&num_cbuf_values), sizeof(num_cbuf_values))
  192. .write(reinterpret_cast<const char*>(&num_cbuf_replacement_values),
  193. sizeof(num_cbuf_replacement_values))
  194. .write(reinterpret_cast<const char*>(&local_memory_size), sizeof(local_memory_size))
  195. .write(reinterpret_cast<const char*>(&texture_bound), sizeof(texture_bound))
  196. .write(reinterpret_cast<const char*>(&start_address), sizeof(start_address))
  197. .write(reinterpret_cast<const char*>(&cached_lowest), sizeof(cached_lowest))
  198. .write(reinterpret_cast<const char*>(&cached_highest), sizeof(cached_highest))
  199. .write(reinterpret_cast<const char*>(&viewport_transform_state),
  200. sizeof(viewport_transform_state))
  201. .write(reinterpret_cast<const char*>(&stage), sizeof(stage))
  202. .write(reinterpret_cast<const char*>(code.data()), code_size);
  203. for (const auto& [key, type] : texture_types) {
  204. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  205. .write(reinterpret_cast<const char*>(&type), sizeof(type));
  206. }
  207. for (const auto& [key, format] : texture_pixel_formats) {
  208. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  209. .write(reinterpret_cast<const char*>(&format), sizeof(format));
  210. }
  211. for (const auto& [key, type] : cbuf_values) {
  212. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  213. .write(reinterpret_cast<const char*>(&type), sizeof(type));
  214. }
  215. for (const auto& [key, type] : cbuf_replacements) {
  216. file.write(reinterpret_cast<const char*>(&key), sizeof(key))
  217. .write(reinterpret_cast<const char*>(&type), sizeof(type));
  218. }
  219. if (stage == Shader::Stage::Compute) {
  220. file.write(reinterpret_cast<const char*>(&workgroup_size), sizeof(workgroup_size))
  221. .write(reinterpret_cast<const char*>(&shared_memory_size), sizeof(shared_memory_size));
  222. } else {
  223. file.write(reinterpret_cast<const char*>(&sph), sizeof(sph));
  224. if (stage == Shader::Stage::Geometry) {
  225. file.write(reinterpret_cast<const char*>(&gp_passthrough_mask),
  226. sizeof(gp_passthrough_mask));
  227. }
  228. }
  229. }
  230. std::optional<u64> GenericEnvironment::TryFindSize() {
  231. static constexpr size_t BLOCK_SIZE = 0x1000;
  232. static constexpr size_t MAXIMUM_SIZE = 0x100000;
  233. static constexpr u64 SELF_BRANCH_A = 0xE2400FFFFF87000FULL;
  234. static constexpr u64 SELF_BRANCH_B = 0xE2400FFFFF07000FULL;
  235. GPUVAddr guest_addr{program_base + start_address};
  236. size_t offset{0};
  237. size_t size{BLOCK_SIZE};
  238. while (size <= MAXIMUM_SIZE) {
  239. code.resize(size / INST_SIZE);
  240. u64* const data = code.data() + offset / INST_SIZE;
  241. gpu_memory->ReadBlock(guest_addr, data, BLOCK_SIZE);
  242. for (size_t index = 0; index < BLOCK_SIZE; index += INST_SIZE) {
  243. const u64 inst = data[index / INST_SIZE];
  244. if (inst == SELF_BRANCH_A || inst == SELF_BRANCH_B) {
  245. return offset + index;
  246. }
  247. }
  248. guest_addr += BLOCK_SIZE;
  249. size += BLOCK_SIZE;
  250. offset += BLOCK_SIZE;
  251. }
  252. return std::nullopt;
  253. }
  254. Tegra::Texture::TICEntry GenericEnvironment::ReadTextureInfo(GPUVAddr tic_addr, u32 tic_limit,
  255. bool via_header_index, u32 raw) {
  256. const auto handle{Tegra::Texture::TexturePair(raw, via_header_index)};
  257. ASSERT(handle.first <= tic_limit);
  258. const GPUVAddr descriptor_addr{tic_addr + handle.first * sizeof(Tegra::Texture::TICEntry)};
  259. Tegra::Texture::TICEntry entry;
  260. gpu_memory->ReadBlock(descriptor_addr, &entry, sizeof(entry));
  261. return entry;
  262. }
  263. GraphicsEnvironment::GraphicsEnvironment(Tegra::Engines::Maxwell3D& maxwell3d_,
  264. Tegra::MemoryManager& gpu_memory_,
  265. Maxwell::ShaderType program, GPUVAddr program_base_,
  266. u32 start_address_)
  267. : GenericEnvironment{gpu_memory_, program_base_, start_address_}, maxwell3d{&maxwell3d_} {
  268. gpu_memory->ReadBlock(program_base + start_address, &sph, sizeof(sph));
  269. initial_offset = sizeof(sph);
  270. gp_passthrough_mask = maxwell3d->regs.post_vtg_shader_attrib_skip_mask;
  271. switch (program) {
  272. case Maxwell::ShaderType::VertexA:
  273. stage = Shader::Stage::VertexA;
  274. stage_index = 0;
  275. break;
  276. case Maxwell::ShaderType::VertexB:
  277. stage = Shader::Stage::VertexB;
  278. stage_index = 0;
  279. break;
  280. case Maxwell::ShaderType::TessellationInit:
  281. stage = Shader::Stage::TessellationControl;
  282. stage_index = 1;
  283. break;
  284. case Maxwell::ShaderType::Tessellation:
  285. stage = Shader::Stage::TessellationEval;
  286. stage_index = 2;
  287. break;
  288. case Maxwell::ShaderType::Geometry:
  289. stage = Shader::Stage::Geometry;
  290. stage_index = 3;
  291. break;
  292. case Maxwell::ShaderType::Pixel:
  293. stage = Shader::Stage::Fragment;
  294. stage_index = 4;
  295. break;
  296. default:
  297. ASSERT_MSG(false, "Invalid program={}", program);
  298. break;
  299. }
  300. const u64 local_size{sph.LocalMemorySize()};
  301. ASSERT(local_size <= std::numeric_limits<u32>::max());
  302. local_memory_size = static_cast<u32>(local_size) + sph.common3.shader_local_memory_crs_size;
  303. texture_bound = maxwell3d->regs.bindless_texture_const_buffer_slot;
  304. is_propietary_driver = texture_bound == 2;
  305. has_hle_engine_state =
  306. maxwell3d->engine_state == Tegra::Engines::Maxwell3D::EngineHint::OnHLEMacro;
  307. }
  308. u32 GraphicsEnvironment::ReadCbufValue(u32 cbuf_index, u32 cbuf_offset) {
  309. const auto& cbuf{maxwell3d->state.shader_stages[stage_index].const_buffers[cbuf_index]};
  310. ASSERT(cbuf.enabled);
  311. u32 value{};
  312. if (cbuf_offset < cbuf.size) {
  313. value = gpu_memory->Read<u32>(cbuf.address + cbuf_offset);
  314. }
  315. cbuf_values.emplace(MakeCbufKey(cbuf_index, cbuf_offset), value);
  316. return value;
  317. }
  318. std::optional<Shader::ReplaceConstant> GraphicsEnvironment::GetReplaceConstBuffer(u32 bank,
  319. u32 offset) {
  320. if (!has_hle_engine_state) {
  321. return std::nullopt;
  322. }
  323. const u64 key = (static_cast<u64>(bank) << 32) | static_cast<u64>(offset);
  324. auto it = maxwell3d->replace_table.find(key);
  325. if (it == maxwell3d->replace_table.end()) {
  326. return std::nullopt;
  327. }
  328. const auto converted_value = [](Tegra::Engines::Maxwell3D::HLEReplacementAttributeType name) {
  329. switch (name) {
  330. case Tegra::Engines::Maxwell3D::HLEReplacementAttributeType::BaseVertex:
  331. return Shader::ReplaceConstant::BaseVertex;
  332. case Tegra::Engines::Maxwell3D::HLEReplacementAttributeType::BaseInstance:
  333. return Shader::ReplaceConstant::BaseInstance;
  334. case Tegra::Engines::Maxwell3D::HLEReplacementAttributeType::DrawID:
  335. return Shader::ReplaceConstant::DrawID;
  336. default:
  337. UNREACHABLE();
  338. }
  339. }(it->second);
  340. cbuf_replacements.emplace(key, converted_value);
  341. return converted_value;
  342. }
  343. Shader::TextureType GraphicsEnvironment::ReadTextureType(u32 handle) {
  344. const auto& regs{maxwell3d->regs};
  345. const bool via_header_index{regs.sampler_binding == Maxwell::SamplerBinding::ViaHeaderBinding};
  346. auto entry =
  347. ReadTextureInfo(regs.tex_header.Address(), regs.tex_header.limit, via_header_index, handle);
  348. const Shader::TextureType result{ConvertTextureType(entry)};
  349. texture_types.emplace(handle, result);
  350. return result;
  351. }
  352. Shader::TexturePixelFormat GraphicsEnvironment::ReadTexturePixelFormat(u32 handle) {
  353. const auto& regs{maxwell3d->regs};
  354. const bool via_header_index{regs.sampler_binding == Maxwell::SamplerBinding::ViaHeaderBinding};
  355. auto entry =
  356. ReadTextureInfo(regs.tex_header.Address(), regs.tex_header.limit, via_header_index, handle);
  357. const Shader::TexturePixelFormat result(ConvertTexturePixelFormat(entry));
  358. texture_pixel_formats.emplace(handle, result);
  359. return result;
  360. }
  361. u32 GraphicsEnvironment::ReadViewportTransformState() {
  362. const auto& regs{maxwell3d->regs};
  363. viewport_transform_state = regs.viewport_scale_offset_enabled;
  364. return viewport_transform_state;
  365. }
  366. ComputeEnvironment::ComputeEnvironment(Tegra::Engines::KeplerCompute& kepler_compute_,
  367. Tegra::MemoryManager& gpu_memory_, GPUVAddr program_base_,
  368. u32 start_address_)
  369. : GenericEnvironment{gpu_memory_, program_base_, start_address_}, kepler_compute{
  370. &kepler_compute_} {
  371. const auto& qmd{kepler_compute->launch_description};
  372. stage = Shader::Stage::Compute;
  373. local_memory_size = qmd.local_pos_alloc + qmd.local_crs_alloc;
  374. texture_bound = kepler_compute->regs.tex_cb_index;
  375. is_propietary_driver = texture_bound == 2;
  376. shared_memory_size = qmd.shared_alloc;
  377. workgroup_size = {qmd.block_dim_x, qmd.block_dim_y, qmd.block_dim_z};
  378. }
  379. u32 ComputeEnvironment::ReadCbufValue(u32 cbuf_index, u32 cbuf_offset) {
  380. const auto& qmd{kepler_compute->launch_description};
  381. ASSERT(((qmd.const_buffer_enable_mask.Value() >> cbuf_index) & 1) != 0);
  382. const auto& cbuf{qmd.const_buffer_config[cbuf_index]};
  383. u32 value{};
  384. if (cbuf_offset < cbuf.size) {
  385. value = gpu_memory->Read<u32>(cbuf.Address() + cbuf_offset);
  386. }
  387. cbuf_values.emplace(MakeCbufKey(cbuf_index, cbuf_offset), value);
  388. return value;
  389. }
  390. Shader::TextureType ComputeEnvironment::ReadTextureType(u32 handle) {
  391. const auto& regs{kepler_compute->regs};
  392. const auto& qmd{kepler_compute->launch_description};
  393. auto entry = ReadTextureInfo(regs.tic.Address(), regs.tic.limit, qmd.linked_tsc != 0, handle);
  394. const Shader::TextureType result{ConvertTextureType(entry)};
  395. texture_types.emplace(handle, result);
  396. return result;
  397. }
  398. Shader::TexturePixelFormat ComputeEnvironment::ReadTexturePixelFormat(u32 handle) {
  399. const auto& regs{kepler_compute->regs};
  400. const auto& qmd{kepler_compute->launch_description};
  401. auto entry = ReadTextureInfo(regs.tic.Address(), regs.tic.limit, qmd.linked_tsc != 0, handle);
  402. const Shader::TexturePixelFormat result(ConvertTexturePixelFormat(entry));
  403. texture_pixel_formats.emplace(handle, result);
  404. return result;
  405. }
  406. u32 ComputeEnvironment::ReadViewportTransformState() {
  407. return viewport_transform_state;
  408. }
  409. void FileEnvironment::Deserialize(std::ifstream& file) {
  410. u64 code_size{};
  411. u64 num_texture_types{};
  412. u64 num_texture_pixel_formats{};
  413. u64 num_cbuf_values{};
  414. u64 num_cbuf_replacement_values{};
  415. file.read(reinterpret_cast<char*>(&code_size), sizeof(code_size))
  416. .read(reinterpret_cast<char*>(&num_texture_types), sizeof(num_texture_types))
  417. .read(reinterpret_cast<char*>(&num_texture_pixel_formats),
  418. sizeof(num_texture_pixel_formats))
  419. .read(reinterpret_cast<char*>(&num_cbuf_values), sizeof(num_cbuf_values))
  420. .read(reinterpret_cast<char*>(&num_cbuf_replacement_values),
  421. sizeof(num_cbuf_replacement_values))
  422. .read(reinterpret_cast<char*>(&local_memory_size), sizeof(local_memory_size))
  423. .read(reinterpret_cast<char*>(&texture_bound), sizeof(texture_bound))
  424. .read(reinterpret_cast<char*>(&start_address), sizeof(start_address))
  425. .read(reinterpret_cast<char*>(&read_lowest), sizeof(read_lowest))
  426. .read(reinterpret_cast<char*>(&read_highest), sizeof(read_highest))
  427. .read(reinterpret_cast<char*>(&viewport_transform_state), sizeof(viewport_transform_state))
  428. .read(reinterpret_cast<char*>(&stage), sizeof(stage));
  429. code.resize(Common::DivCeil(code_size, sizeof(u64)));
  430. file.read(reinterpret_cast<char*>(code.data()), code_size);
  431. for (size_t i = 0; i < num_texture_types; ++i) {
  432. u32 key;
  433. Shader::TextureType type;
  434. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  435. .read(reinterpret_cast<char*>(&type), sizeof(type));
  436. texture_types.emplace(key, type);
  437. }
  438. for (size_t i = 0; i < num_texture_pixel_formats; ++i) {
  439. u32 key;
  440. Shader::TexturePixelFormat format;
  441. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  442. .read(reinterpret_cast<char*>(&format), sizeof(format));
  443. texture_pixel_formats.emplace(key, format);
  444. }
  445. for (size_t i = 0; i < num_cbuf_values; ++i) {
  446. u64 key;
  447. u32 value;
  448. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  449. .read(reinterpret_cast<char*>(&value), sizeof(value));
  450. cbuf_values.emplace(key, value);
  451. }
  452. for (size_t i = 0; i < num_cbuf_replacement_values; ++i) {
  453. u64 key;
  454. Shader::ReplaceConstant value;
  455. file.read(reinterpret_cast<char*>(&key), sizeof(key))
  456. .read(reinterpret_cast<char*>(&value), sizeof(value));
  457. cbuf_replacements.emplace(key, value);
  458. }
  459. if (stage == Shader::Stage::Compute) {
  460. file.read(reinterpret_cast<char*>(&workgroup_size), sizeof(workgroup_size))
  461. .read(reinterpret_cast<char*>(&shared_memory_size), sizeof(shared_memory_size));
  462. initial_offset = 0;
  463. } else {
  464. file.read(reinterpret_cast<char*>(&sph), sizeof(sph));
  465. initial_offset = sizeof(sph);
  466. if (stage == Shader::Stage::Geometry) {
  467. file.read(reinterpret_cast<char*>(&gp_passthrough_mask), sizeof(gp_passthrough_mask));
  468. }
  469. }
  470. is_propietary_driver = texture_bound == 2;
  471. }
  472. void FileEnvironment::Dump(u64 pipeline_hash, u64 shader_hash) {
  473. DumpImpl(pipeline_hash, shader_hash, code, read_highest, read_lowest, initial_offset, stage);
  474. }
  475. u64 FileEnvironment::ReadInstruction(u32 address) {
  476. if (address < read_lowest || address > read_highest) {
  477. throw Shader::LogicError("Out of bounds address {}", address);
  478. }
  479. return code[(address - read_lowest) / sizeof(u64)];
  480. }
  481. u32 FileEnvironment::ReadCbufValue(u32 cbuf_index, u32 cbuf_offset) {
  482. const auto it{cbuf_values.find(MakeCbufKey(cbuf_index, cbuf_offset))};
  483. if (it == cbuf_values.end()) {
  484. throw Shader::LogicError("Uncached read texture type");
  485. }
  486. return it->second;
  487. }
  488. Shader::TextureType FileEnvironment::ReadTextureType(u32 handle) {
  489. const auto it{texture_types.find(handle)};
  490. if (it == texture_types.end()) {
  491. throw Shader::LogicError("Uncached read texture type");
  492. }
  493. return it->second;
  494. }
  495. Shader::TexturePixelFormat FileEnvironment::ReadTexturePixelFormat(u32 handle) {
  496. const auto it{texture_pixel_formats.find(handle)};
  497. if (it == texture_pixel_formats.end()) {
  498. throw Shader::LogicError("Uncached read texture pixel format");
  499. }
  500. return it->second;
  501. }
  502. u32 FileEnvironment::ReadViewportTransformState() {
  503. return viewport_transform_state;
  504. }
  505. u32 FileEnvironment::LocalMemorySize() const {
  506. return local_memory_size;
  507. }
  508. u32 FileEnvironment::SharedMemorySize() const {
  509. return shared_memory_size;
  510. }
  511. u32 FileEnvironment::TextureBoundBuffer() const {
  512. return texture_bound;
  513. }
  514. std::array<u32, 3> FileEnvironment::WorkgroupSize() const {
  515. return workgroup_size;
  516. }
  517. std::optional<Shader::ReplaceConstant> FileEnvironment::GetReplaceConstBuffer(u32 bank,
  518. u32 offset) {
  519. const u64 key = (static_cast<u64>(bank) << 32) | static_cast<u64>(offset);
  520. auto it = cbuf_replacements.find(key);
  521. if (it == cbuf_replacements.end()) {
  522. return std::nullopt;
  523. }
  524. return it->second;
  525. }
  526. void SerializePipeline(std::span<const char> key, std::span<const GenericEnvironment* const> envs,
  527. const std::filesystem::path& filename, u32 cache_version) try {
  528. std::ofstream file(filename, std::ios::binary | std::ios::ate | std::ios::app);
  529. file.exceptions(std::ifstream::failbit);
  530. if (!file.is_open()) {
  531. LOG_ERROR(Common_Filesystem, "Failed to open pipeline cache file {}",
  532. Common::FS::PathToUTF8String(filename));
  533. return;
  534. }
  535. if (file.tellp() == 0) {
  536. // Write header
  537. file.write(MAGIC_NUMBER.data(), MAGIC_NUMBER.size())
  538. .write(reinterpret_cast<const char*>(&cache_version), sizeof(cache_version));
  539. }
  540. if (!std::ranges::all_of(envs, &GenericEnvironment::CanBeSerialized)) {
  541. return;
  542. }
  543. const u32 num_envs{static_cast<u32>(envs.size())};
  544. file.write(reinterpret_cast<const char*>(&num_envs), sizeof(num_envs));
  545. for (const GenericEnvironment* const env : envs) {
  546. env->Serialize(file);
  547. }
  548. file.write(key.data(), key.size_bytes());
  549. } catch (const std::ios_base::failure& e) {
  550. LOG_ERROR(Common_Filesystem, "{}", e.what());
  551. if (!Common::FS::RemoveFile(filename)) {
  552. LOG_ERROR(Common_Filesystem, "Failed to delete pipeline cache file {}",
  553. Common::FS::PathToUTF8String(filename));
  554. }
  555. }
  556. void LoadPipelines(
  557. std::stop_token stop_loading, const std::filesystem::path& filename, u32 expected_cache_version,
  558. Common::UniqueFunction<void, std::ifstream&, FileEnvironment> load_compute,
  559. Common::UniqueFunction<void, std::ifstream&, std::vector<FileEnvironment>> load_graphics) try {
  560. std::ifstream file(filename, std::ios::binary | std::ios::ate);
  561. if (!file.is_open()) {
  562. return;
  563. }
  564. file.exceptions(std::ifstream::failbit);
  565. const auto end{file.tellg()};
  566. file.seekg(0, std::ios::beg);
  567. std::array<char, 8> magic_number;
  568. u32 cache_version;
  569. file.read(magic_number.data(), magic_number.size())
  570. .read(reinterpret_cast<char*>(&cache_version), sizeof(cache_version));
  571. if (magic_number != MAGIC_NUMBER || cache_version != expected_cache_version) {
  572. file.close();
  573. if (Common::FS::RemoveFile(filename)) {
  574. if (magic_number != MAGIC_NUMBER) {
  575. LOG_ERROR(Common_Filesystem, "Invalid pipeline cache file");
  576. }
  577. if (cache_version != expected_cache_version) {
  578. LOG_INFO(Common_Filesystem, "Deleting old pipeline cache");
  579. }
  580. } else {
  581. LOG_ERROR(Common_Filesystem,
  582. "Invalid pipeline cache file and failed to delete it in \"{}\"",
  583. Common::FS::PathToUTF8String(filename));
  584. }
  585. return;
  586. }
  587. while (file.tellg() != end) {
  588. if (stop_loading.stop_requested()) {
  589. return;
  590. }
  591. u32 num_envs{};
  592. file.read(reinterpret_cast<char*>(&num_envs), sizeof(num_envs));
  593. std::vector<FileEnvironment> envs(num_envs);
  594. for (FileEnvironment& env : envs) {
  595. env.Deserialize(file);
  596. }
  597. if (envs.front().ShaderStage() == Shader::Stage::Compute) {
  598. load_compute(file, std::move(envs.front()));
  599. } else {
  600. load_graphics(file, std::move(envs));
  601. }
  602. }
  603. } catch (const std::ios_base::failure& e) {
  604. LOG_ERROR(Common_Filesystem, "{}", e.what());
  605. if (!Common::FS::RemoveFile(filename)) {
  606. LOG_ERROR(Common_Filesystem, "Failed to delete pipeline cache file {}",
  607. Common::FS::PathToUTF8String(filename));
  608. }
  609. }
  610. } // namespace VideoCommon