mod.rs 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057
  1. //! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute
  2. //! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts.
  3. //! Compute shaders keep the console's thread-group size; one that depends
  4. //! on the lane layout (cross-lane operations) declares the console's wave
  5. //! size (`WaveSize`), so the host device must support it.
  6. //!
  7. //! What the host binds for a translated shader ([`HostShader`]):
  8. //!
  9. //! * **User data** at `b0, space 0` (32-bit root constants or a constant
  10. //! buffer, per stage): dword `index` holds a root parameter's value, as
  11. //! [`UserData`] lists. A root-constant dword is the constant. A
  12. //! descriptor table is the byte offset of its first descriptor in its
  13. //! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16
  14. //! for sampler tables (the console's descriptor sizes; the code adds
  15. //! offsets in those units). The heap bases of dynamic resources are 0
  16. //! and not listed.
  17. //! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and
  18. //! `SamplerDescriptorHeap[]`, at the index the console address gives, so
  19. //! the host heaps keep the title's descriptor order. The root signature
  20. //! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and
  21. //! `SAMPLER_HEAP_DIRECTLY_INDEXED`.
  22. //! * **Immediate samplers** as static samplers `s<n>, space 0`, `n` the
  23. //! position in [`HostShader::samplers`] (the console sampler words) and
  24. //! [`HostShader::static_samplers`] (the same decoded into a D3D12 static
  25. //! sampler description). Comparison sampling (added 2026-11-23): an
  26. //! immediate sampler it uses has a comparison filter there (bit 0x80);
  27. //! a heap sampler it uses must be a comparison sampler on the host.
  28. //! * **Root CBVs and root SRVs** (raw buffers) as root descriptors
  29. //! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter
  30. //! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the
  31. //! address the title sets is the buffer's.
  32. //! * **Vertex fetch** (added 2026-11-23). The title's mesh and
  33. //! vertex programs fetch vertices themselves with typed-format loads
  34. //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm,
  35. //! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the
  36. //! instruction, so the translation reads raw bytes and converts them
  37. //! itself. Their descriptors are built around a root SRV (stride 1, no
  38. //! record limit): the host binds the root SRV `t<slot>` above with the
  39. //! address the title sets, nothing more. The vertex index, the stride
  40. //! and the attribute offset are the shader's own arithmetic on data in
  41. //! that buffer (per-stream headers), not descriptor fields.
  42. //! * **Buffer views in the heap** are declared by how the shader reads
  43. //! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and
  44. //! typed-format loads without an index; structured with the used-resource
  45. //! entry's stride when indexed; typed with four 32-bit float channels for
  46. //! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at
  47. //! that index must be of that kind and start at the console descriptor's
  48. //! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the
  49. //! title's view description says. Typed-format loads from heap
  50. //! descriptors (1,024 world compute programs, ray-tracing material
  51. //! resolves) read raw views this way.
  52. //!
  53. //! * **Texture atomics** use a scalar integer UAV. The host binds R32_UINT
  54. //! for 32-bit operations and R32G32_UINT for 64-bit operations. The latter
  55. //! require SM 6.6 atomic support on typed and descriptor-heap resources.
  56. //!
  57. //! Entry points: [`translate`] (container bytes as the title passes them
  58. //! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
  59. //! earlier stages already run). The root constants of each stage must
  60. //! cover [`HostShader::user_data_dwords`]. Stability: these types and the
  61. //! binding scheme are what pipeline creation builds on; changes are
  62. //! announced.
  63. //! * **Signatures** as the console container has them (same semantics,
  64. //! registers and masks), so the input layout and stage linking are the
  65. //! title's; pixel outputs are plain 32-bit values.
  66. //! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and
  67. //! descriptors as above (the root constants visible to the mesh stage);
  68. //! the pipeline is a mesh pipeline (pipeline-state stream, no input
  69. //! layout) with the title's pixel shader. The thread group is the
  70. //! console's in lanes (`[numthreads]` in the DXIL), the vertex and
  71. //! primitive maxima its own, triangles only, no wave size required. The
  72. //! console numbers groups in x only: the draw path passes the title's
  73. //! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
  74. //! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
  75. //! console never exports them).
  76. //! * **Rectangle lists** ([`rect_list_gs`], `gs_6_6`): the console draws a
  77. //! rectangle from three vertices; the host has no such topology. A
  78. //! pipeline the title makes for rectangles (topology type 19) gets a
  79. //! geometry shader of ours between the translated vertex and pixel
  80. //! shaders and draws triangle lists with the title's own vertex counts.
  81. //! It binds nothing.
  82. mod bitcode;
  83. mod container;
  84. #[cfg(all(test, windows))]
  85. mod diff_tests;
  86. #[cfg(all(test, windows))]
  87. mod intersect_tests;
  88. #[cfg(all(windows, any(test, feature = "host")))]
  89. pub mod host;
  90. mod lower;
  91. mod own_bits;
  92. #[cfg(all(test, windows))]
  93. mod permlane_tests;
  94. mod rect;
  95. mod sampler;
  96. mod shader;
  97. mod threading;
  98. #[cfg(windows)]
  99. pub mod validator;
  100. #[cfg(all(test, windows))]
  101. mod size_tests;
  102. #[cfg(all(test, windows))]
  103. mod valu_tests;
  104. #[cfg(all(test, windows))]
  105. mod waterfall_tests;
  106. #[cfg(all(test, windows))]
  107. mod wave64_tests;
  108. mod wave;
  109. use crate::dxbc::{Container, FourCC};
  110. use crate::native::{HwStage, NativeProgram, RootType};
  111. use crate::{ShaderError, io, ir, resource, structure};
  112. pub use bitcode::census;
  113. pub use sampler::StaticSampler;
  114. pub use lower::{host_settings, set_host_max_wave};
  115. pub use rect::rect_list_gs;
  116. pub use shader::{
  117. MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
  118. SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
  119. set_view_heap_limit, view_heap_limit,
  120. };
  121. /// The loop limit without an override: 2^20.
  122. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT;
  123. /// The iteration count after which a translated loop is left, per lane and
  124. /// per entry into the loop: [`DEFAULT_LOOP_LIMIT`].
  125. ///
  126. /// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or
  127. /// `0x` hex, at least 1) sets it instead. A loop that hits the limit in
  128. /// every lane of a full-screen pass still runs for seconds (2^20 times a
  129. /// 4K screen is about 10^13 iterations); a much lower limit shows whether
  130. /// such loops are what makes a frame slow. The value is part of the
  131. /// translation, so the shader cache must key on it (`victory-gpu`'s does).
  132. pub fn loop_limit() -> u32 {
  133. static LIMIT: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  134. *LIMIT.get_or_init(|| {
  135. if cfg!(feature = "diagnostics") {
  136. parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref())
  137. } else {
  138. lower::LOOP_LIMIT
  139. }
  140. })
  141. }
  142. /// Whether a pixel shader's helper lane reads its own value where the console reads the first
  143. /// lane's (`lower.rs` `first_lane`); on unless `VICTORY_HELPER_OWN=0`. Part of the translation:
  144. /// the shader cache keys on it.
  145. pub fn helper_own() -> bool {
  146. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  147. *ON.get_or_init(|| std::env::var_os("VICTORY_HELPER_OWN").is_none_or(|v| v != "0"))
  148. }
  149. /// Which of a translated program's group barriers wait for the whole
  150. /// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory
  151. /// fence and lose the wait. A wait that some thread of the group never
  152. /// reaches is undefined on the host, and NVIDIA's wait is for every
  153. /// thread: the group stands until Windows resets the card. (The console's
  154. /// barrier is the wave's, whatever lanes are live, and a wave that ended
  155. /// is not waited for.) `VICTORY_GROUP_SYNC`:
  156. /// - unset or `2`: every barrier waits, as before.
  157. /// - `1`: the title's `s_barrier` waits only in a block every lane runs,
  158. /// in a program no lane can be cut out of at the iteration limit.
  159. /// - `0`: no barrier waits, neither the title's nor the ones the
  160. /// translation adds (wave64 programs in two host waves exchange through
  161. /// them, so such programs compute wrong values). For one run that tells
  162. /// whether a barrier is what stops the card: with it no run can stand in
  163. /// a barrier.
  164. ///
  165. /// Part of the translation: the shader cache keys on it (`victory-gpu`'s
  166. /// does).
  167. pub fn group_sync() -> u8 {
  168. static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  169. *MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) {
  170. Some("0") => 0,
  171. Some("1") => 1,
  172. _ => 2,
  173. })
  174. }
  175. /// The clean-up passes that run over a translated program before it is
  176. /// written (`bitcode::opt`): a set of that module's pass bits. Every pass
  177. /// is exact, so the switch is for telling a translator fault from a
  178. /// clean-up fault, and for measuring what the clean-up is worth.
  179. /// `VICTORY_SHADER_OPT`:
  180. /// - unset: every pass.
  181. /// - `0`: none (the module as the lowering made it).
  182. /// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants
  183. /// and identities, 4 one instruction for one value, 8 what a branch taken
  184. /// says about its condition, 16 one read for one place within a block,
  185. /// 32 a first-lane read of two host waves without the round that asks
  186. /// which half has a lane (where every lane has one).
  187. ///
  188. /// Part of the translation: the shader cache keys on it (`victory-gpu`'s
  189. /// does).
  190. pub fn shader_opt() -> u32 {
  191. static PASSES: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  192. *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref()))
  193. }
  194. /// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or
  195. /// unreadable. Pure, for testing.
  196. fn parse_shader_opt(value: Option<&str>) -> u32 {
  197. let parsed = value
  198. .map(str::trim)
  199. .and_then(|v| match v.strip_prefix("0x") {
  200. Some(hex) => u32::from_str_radix(hex, 16).ok(),
  201. None => v.parse().ok(),
  202. });
  203. parsed.map_or(bitcode::opt::ALL, |n| n & bitcode::opt::ALL)
  204. }
  205. /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
  206. /// unreadable or 0. Pure, for testing.
  207. fn parse_loop_limit(value: Option<&str>) -> u32 {
  208. let parsed = value
  209. .map(str::trim)
  210. .and_then(|v| match v.strip_prefix("0x") {
  211. Some(hex) => u32::from_str_radix(hex, 16).ok(),
  212. None => v.parse().ok(),
  213. });
  214. match parsed {
  215. Some(n) if n > 0 => n,
  216. _ => lower::LOOP_LIMIT,
  217. }
  218. }
  219. /// A translated shader and what the host binds for it.
  220. #[derive(Debug, Clone, PartialEq, Eq)]
  221. pub struct HostShader {
  222. pub stage: HwStage,
  223. /// The DXIL container, hashed as D3D12 expects.
  224. pub dxil: Vec<u8>,
  225. /// The user-data dwords the shader reads.
  226. pub user_data: Vec<UserData>,
  227. /// Immediate samplers: the four sampler words of `s<n>`.
  228. pub samplers: Vec<[u32; 4]>,
  229. /// The same samplers decoded, `s<n>` at position n: the static sampler
  230. /// descriptions the host's root signature declares.
  231. pub static_samplers: Vec<StaticSampler>,
  232. /// Root CBVs the shader reads: root parameter indices, each bound as
  233. /// `b<index>` in [`ROOT_CBV_SPACE`].
  234. pub root_cbvs: Vec<u8>,
  235. /// Root SRVs (raw buffers) the shader reads: `t<index>` in
  236. /// [`ROOT_CBV_SPACE`].
  237. pub root_srvs: Vec<u8>,
  238. /// Root UAVs (raw buffers) the shader reads or writes: `u<index>` in
  239. /// [`ROOT_CBV_SPACE`].
  240. pub root_uavs: Vec<u8>,
  241. /// Heap descriptors that can be selected from root state at bind time.
  242. pub root_indexed_views: Vec<crate::resource::RootIndexedView>,
  243. }
  244. impl HostShader {
  245. /// Size of the user-data buffer the shader declares, in dwords (a
  246. /// multiple of 4; 0 when it reads none). Root constants must cover it.
  247. pub fn user_data_dwords(&self) -> u32 {
  248. let n = self
  249. .user_data
  250. .iter()
  251. .map(|u| u.index + 1)
  252. .max()
  253. .unwrap_or(0);
  254. n.next_multiple_of(4)
  255. }
  256. }
  257. /// One dword of user data and the root parameter that fills it.
  258. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  259. pub struct UserData {
  260. /// Dword in the user-data buffer (the console's user-data index).
  261. pub index: u32,
  262. /// Root parameter index in the title's root signature.
  263. pub slot: u8,
  264. /// `Constants` or `Table` (see the module notes for the value).
  265. pub root: RootType,
  266. /// Dword within the parameter.
  267. pub dword: u32,
  268. }
  269. /// Translates the vertex, pixel, compute or mesh program of a console
  270. /// shader container.
  271. pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
  272. let c = Container::parse(container)?;
  273. let dxil = c
  274. .part(FourCC::DXIL)
  275. .or(c.part(FourCC::ACCC))
  276. .ok_or(ShaderError::Malformed("no DXIL part"))?;
  277. let native = crate::native_programs(dxil.data)?
  278. .into_iter()
  279. .find(|p| {
  280. matches!(
  281. p.stage,
  282. HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms
  283. )
  284. })
  285. .ok_or(ShaderError::Unsupported {
  286. offset: 0,
  287. what: "a container without a vertex, pixel, compute or mesh program",
  288. })?;
  289. let p = crate::spill::build(&native)?;
  290. // Structurisation first: tracing per-lane descriptors needs it (its
  291. // failure is reported after the earlier stages').
  292. let st = structure::structure(&p);
  293. let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?;
  294. let io = io::raise(&p, &native)?;
  295. let st = st?;
  296. emit(&c, &native, &p, &st, &io, &res)
  297. }
  298. /// Emits a program whose earlier stages already ran.
  299. pub fn emit(
  300. c: &Container,
  301. native: &NativeProgram,
  302. p: &ir::Program,
  303. st: &structure::Structured,
  304. io: &io::Io,
  305. res: &resource::Resources,
  306. ) -> Result<HostShader, ShaderError> {
  307. // (what an earlier program's lowering on this thread left behind)
  308. lower::take_needs();
  309. let original = emit_program(c, native, p, st, io, res);
  310. // A console wave64 compute program on a host of 32-lane waves that
  311. // still needs 64 lanes, or whose cross-lane code sits where not every
  312. // lane runs: once more with its early-outs left out
  313. // ([`ir::without_early_outs`]), which is what usually keeps the whole
  314. // body from being a block every lane runs.
  315. let stuck = match &original {
  316. Ok((_, wave)) => *wave == Some(64),
  317. Err(ShaderError::Unsupported { what, .. }) => lower::needs_every_lane(what),
  318. Err(_) => false,
  319. };
  320. // (a mask with lanes elsewhere is only helped by the exact forms: not by each half-wave
  321. // on its own)
  322. let exact_only = matches!(&original, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE);
  323. if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 {
  324. let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
  325. let report = |what: &str, r: &Result<(HostShader, Option<u32>), ShaderError>| {
  326. if why {
  327. match r {
  328. Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"),
  329. Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"),
  330. }
  331. }
  332. };
  333. let done = |r: &Result<(HostShader, Option<u32>), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64));
  334. // Each host wave as a wave of its own (`lower::with_local_waves`),
  335. // for programs still stopped where not every lane runs.
  336. let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0");
  337. // Where the wave operations are the allocation idiom
  338. // ([`lower::wave_local`]) that is exact. Other programs are taken
  339. // the same way last of all, each half-wave giving its own results
  340. // (approximate: a tile-wide result becomes two half-tile ones);
  341. // `VICTORY_WAVE_LOCAL=idiom` refuses those instead.
  342. let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom");
  343. let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) {
  344. Ok(()) => true,
  345. Err((offset, what)) => {
  346. if why {
  347. eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}");
  348. }
  349. false
  350. }
  351. };
  352. // The program in two other forms: without its early-outs, and
  353. // without any branch that only skips code no lane is left for.
  354. let form = |p: Option<ir::Program>| {
  355. p.and_then(|p| {
  356. let st = structure::structure(&p).ok()?;
  357. let io = io::raise(&p, native).ok()?;
  358. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?;
  359. Some((p, st, io, res))
  360. })
  361. };
  362. let forms = [
  363. ("without early-outs", form(ir::without_early_outs(p))),
  364. ("without skips", form(ir::without_skips(p, false))),
  365. ];
  366. for (name, f) in &forms {
  367. if let Some((p, st, io, res)) = f {
  368. let again = emit_program(c, native, p, st, io, res);
  369. report(name, &again);
  370. if done(&again) {
  371. return again.map(|(shader, _)| shader);
  372. }
  373. }
  374. }
  375. // Off unless asked for (`VICTORY_WAVE_WIDE=1`), for a console wave run as two host
  376. // waves: this form puts group barriers inside branches and loops, and runs 121-124
  377. // lost the card in a submission of two programs that had just moved to it
  378. // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which
  379. // has no barrier, stays on.
  380. let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1");
  381. // exact first: each host wave on its own where that is exact (the idiom, every
  382. // form; no barriers), then the other exact forms; then approximate
  383. for exact in [true, false] {
  384. if !exact {
  385. // Before anything approximate, the exact forms that cost group barriers.
  386. // Every skip left out that the code after it cannot see
  387. // ([`ir::without_skips`], `deep`): most of the body is then code every
  388. // lane runs, where the two host waves can exchange.
  389. // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.)
  390. let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0");
  391. let deep = if deep_on { form(ir::without_skips(p, true)) } else { None };
  392. if let Some((p, st, io, res)) = &deep {
  393. let again = emit_program(c, native, p, st, io, res);
  394. report("without skips, scalars followed", &again);
  395. if done(&again) {
  396. return again.map(|(shader, _)| shader);
  397. }
  398. }
  399. // Still stopped where not every lane runs: the per-lane branches around
  400. // those places taken as the console takes them, by the whole wave at once
  401. // ([`widen`]), at two group barriers per such branch.
  402. if wide_on {
  403. let bases = [
  404. deep.as_ref().map(|f| &f.0),
  405. forms[1].1.as_ref().map(|f| &f.0),
  406. forms[0].1.as_ref().map(|f| &f.0),
  407. Some(p),
  408. ];
  409. if let Some(base) = bases.into_iter().flatten().next() {
  410. let again = widen(c, native, base, why);
  411. report("wave-wide branches", &again);
  412. if done(&again) {
  413. return again.map(|(shader, _)| shader);
  414. }
  415. }
  416. }
  417. if strict {
  418. break;
  419. }
  420. }
  421. if !local_on || exact_only {
  422. continue;
  423. }
  424. for (name, f) in &forms {
  425. if let Some((p, st, io, res)) = f
  426. && idiom(p, st) == exact
  427. {
  428. let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
  429. report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local);
  430. if done(&local) {
  431. return local.map(|(shader, _)| shader);
  432. }
  433. }
  434. }
  435. if idiom(p, st) == exact {
  436. let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
  437. report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local);
  438. if done(&local) {
  439. return local.map(|(shader, _)| shader);
  440. }
  441. }
  442. }
  443. if local_on && !exact_only {
  444. // Last: every mask and lane read per host wave.
  445. if !strict {
  446. for (name, f) in &forms {
  447. if let Some((p, st, io, res)) = f {
  448. let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
  449. report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local);
  450. if done(&local) {
  451. return local.map(|(shader, _)| shader);
  452. }
  453. }
  454. }
  455. let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
  456. report("local waves (APPROXIMATE, any mask)", &local);
  457. if done(&local) {
  458. return local.map(|(shader, _)| shader);
  459. }
  460. }
  461. }
  462. }
  463. // SCC of a mask operation joined with a scalar test behind a per-lane skip (the 32-lane
  464. // trace programs): right once the wave takes that skip together ([`widen`]; the
  465. // lowering has named the skipped blocks).
  466. let original = match original {
  467. Err(ShaderError::Unsupported { what, .. })
  468. if native.stage == HwStage::Cs
  469. && what == lower::LANE_MASK
  470. && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") =>
  471. {
  472. let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some());
  473. match again {
  474. Ok(_) => again,
  475. Err(_) => emit_program(c, native, p, st, io, res),
  476. }
  477. }
  478. other => other,
  479. };
  480. let original = original.map(|(shader, _)| shader);
  481. // Retry unsupported programs only. Threading can separate an unknown
  482. // register value from its apparent use on a mutually exclusive path.
  483. if !matches!(original, Err(ShaderError::Unsupported { .. })) {
  484. return original;
  485. }
  486. let edges = threading::constant_edges(p, st);
  487. if edges.is_empty() {
  488. return original;
  489. }
  490. let p = ir::thread_edges(p, &edges)?;
  491. let st = structure::structure(&p)?;
  492. let io = io::raise(&p, native)?;
  493. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  494. emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader)
  495. }
  496. /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane
  497. /// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the
  498. /// lowering names the blocks where the two host waves must meet and could not
  499. /// (`lower::take_needs`), the branches whose regions hold them are widened, and so on until
  500. /// it translates or a branch cannot be widened. Only where a thread group is one console
  501. /// wave: with several, the waves of a group would decide differently and a barrier inside
  502. /// such a branch would wait for threads that never come.
  503. fn widen(
  504. c: &Container,
  505. native: &NativeProgram,
  506. p: &ir::Program,
  507. why: bool,
  508. ) -> Result<(HostShader, Option<u32>), ShaderError> {
  509. const NOT: ShaderError = ShaderError::Unsupported {
  510. offset: 0,
  511. what: "wave-wide branches in a thread group of several console waves",
  512. };
  513. match native.io {
  514. // (a program whose waves are the host's meets no one: no barrier, any group)
  515. crate::native::StageIo::Cs(_) if !(native.wave64 && lower::host_max_wave() == 32) => {}
  516. crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64 => {}
  517. crate::native::StageIo::Cs(cs) => {
  518. if why {
  519. eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads);
  520. }
  521. return Err(NOT);
  522. }
  523. _ => return Err(NOT),
  524. }
  525. let mut wide = std::collections::HashSet::new();
  526. loop {
  527. let st = structure::structure_wide(p, &wide)?;
  528. let io = io::raise(p, native)?;
  529. let res = resource::track(p, &native.layout, native.stage, Some(&st))?;
  530. lower::take_needs();
  531. let r = emit_program(c, native, p, &st, &io, &res);
  532. let needs = lower::take_needs();
  533. // (or translated for 64-lane waves still: shared memory read and written where not
  534. // every lane runs, whose blocks the lowering names too)
  535. let stuck = matches!(&r, Err(ShaderError::Unsupported { what, .. })
  536. if lower::needs_every_lane(what) || *what == lower::LANE_MASK && !needs.is_empty())
  537. || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty();
  538. if !stuck {
  539. if why {
  540. eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len());
  541. }
  542. return r;
  543. }
  544. let more: Vec<usize> = lower::branches_around(&st, &needs)
  545. .unwrap_or_default()
  546. .into_iter()
  547. .filter(|b| !wide.contains(b))
  548. .collect();
  549. if more.is_empty() {
  550. if why {
  551. eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len());
  552. }
  553. return r;
  554. }
  555. wide.extend(more);
  556. }
  557. }
  558. /// The translated program, and the wave size it requires of the host.
  559. fn emit_program(
  560. c: &Container,
  561. native: &NativeProgram,
  562. p: &ir::Program,
  563. st: &structure::Structured,
  564. io: &io::Io,
  565. res: &resource::Resources,
  566. ) -> Result<(HostShader, Option<u32>), ShaderError> {
  567. let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
  568. match c.part(fourcc) {
  569. Some(part) => signature(part.data),
  570. None => Ok(Vec::new()),
  571. }
  572. };
  573. let pixel = native.stage == HwStage::Ps;
  574. let mut inputs = sig(FourCC::ISG1)?;
  575. let mut outputs = sig(FourCC::OSG1)?;
  576. // Interpolation as DXC declares it by default; pixel inputs that are
  577. // read get the mode their barycentrics say.
  578. let interpolated = if pixel { &mut inputs } else { &mut outputs };
  579. for e in interpolated {
  580. e.interp = match (e.kind, e.comp) {
  581. (3, _) => 4,
  582. // Constant, as DXC declares it (the AMD compiler crashed on a
  583. // front face without a mode).
  584. (13, _) => 1,
  585. // Until a read says which mode (`lower`).
  586. (28, _) => 2,
  587. (0 | 6 | 7, 9) => 2,
  588. (0, _) => 1,
  589. _ => 0,
  590. };
  591. }
  592. // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL
  593. // wants the position centroid (or per sample), as DXC declares it then.
  594. if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) {
  595. for e in inputs.iter_mut().filter(|e| e.kind == 3) {
  596. e.interp = 5;
  597. }
  598. }
  599. // Per-primitive outputs are constant. The console never exports a
  600. // primitive id or cull flag a mesh shader writes (it culls with the
  601. // primitive export), so those rows are left out.
  602. let mut prims = sig(FourCC::PSG1)?;
  603. prims.retain(|e| !matches!(e.kind, 10 | 30));
  604. for e in &mut prims {
  605. e.interp = 1;
  606. }
  607. // A mesh group's id arrives multiplied by max(threads, vertices,
  608. // primitives) (the code divides by that); the thread count is in PSV0
  609. // from runtime info version 2 on.
  610. // shortcut: older containers fall back to the group's lane count, right
  611. // when the HLSL group fills its waves (the title's do).
  612. let mesh_stride = match &native.io {
  613. crate::native::StageIo::Ms(ms) => {
  614. let psv = c.part(FourCC::PSV0).map(|p| p.data);
  615. let threads = psv
  616. .filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48))
  617. .and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok());
  618. threads.map_or(ms.threads, |t| {
  619. t.max(ms.max_vertices).max(ms.max_primitives)
  620. })
  621. }
  622. _ => 0,
  623. };
  624. let l = lower::lower(&lower::Parts {
  625. native,
  626. p,
  627. st,
  628. io,
  629. res,
  630. inputs,
  631. outputs,
  632. prims,
  633. mesh_stride,
  634. })?;
  635. let wave_size = l.wave_size;
  636. let shader = HostShader {
  637. stage: native.stage,
  638. dxil: l.dxil,
  639. user_data: l.user_data,
  640. static_samplers: l
  641. .samplers
  642. .iter()
  643. .enumerate()
  644. .map(|(n, &w)| {
  645. let mut s = StaticSampler::from_words(w);
  646. if l.cmp_samplers >> n & 1 != 0 {
  647. s.filter |= 0x80;
  648. }
  649. s
  650. })
  651. .collect(),
  652. samplers: l.samplers,
  653. root_cbvs: l.root_cbvs,
  654. root_srvs: l.root_srvs,
  655. root_uavs: l.root_uavs,
  656. root_indexed_views: res.root_indexed_views.clone(),
  657. };
  658. Ok((shader, wave_size))
  659. }
  660. /// The rows of an `ISG1`/`OSG1` part.
  661. fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
  662. use crate::dxbc::u32_at;
  663. let count = u32_at(part, 0)? as usize;
  664. let base = u32_at(part, 4)? as usize;
  665. let mut out = Vec::with_capacity(count);
  666. for i in 0..count {
  667. let at = base + 32 * i;
  668. let name_at = u32_at(part, at + 4)? as usize;
  669. let name = part
  670. .get(name_at..)
  671. .and_then(|s| s.split(|&b| b == 0).next())
  672. .ok_or(ShaderError::Malformed("signature name out of bounds"))?;
  673. let mask = *part
  674. .get(at + 24)
  675. .ok_or(ShaderError::Malformed("truncated"))?;
  676. if u32_at(part, at + 28)? != 0 {
  677. return Err(ShaderError::Unsupported {
  678. offset: 0,
  679. what: "a minimum-precision signature element",
  680. });
  681. }
  682. if u32_at(part, at)? != 0 {
  683. return Err(ShaderError::Unsupported {
  684. offset: 0,
  685. what: "a signature element of another stream",
  686. });
  687. }
  688. let kind = match u32_at(part, at + 12)? {
  689. 0 => 0,
  690. 1 => 3,
  691. 2 => 6,
  692. 3 => 7,
  693. 4 => 4,
  694. 5 => 5,
  695. 6 => 1,
  696. 7 => 10,
  697. 8 => 2,
  698. 9 => 13,
  699. 10 => 12,
  700. 64 => 16,
  701. 65 => 17,
  702. 66 => 14,
  703. 67 => 19,
  704. 68 => 18,
  705. 69 => 20,
  706. 70 => 15,
  707. 23 => 28, // barycentrics
  708. 25 => 30, // cull primitive
  709. _ => {
  710. return Err(ShaderError::Unsupported {
  711. offset: 0,
  712. what: "a system value in the signature",
  713. });
  714. }
  715. };
  716. // 16-bit elements are declared 32-bit; reading or writing one
  717. // converts (16-bit values travel packed on the console).
  718. let raw = u32_at(part, at + 16)?;
  719. let comp = match (kind, raw) {
  720. // DXIL declares the front face a uint (the validator insists).
  721. (13, _) => 5,
  722. (_, 1 | 4) => 5,
  723. (_, 2 | 5) => 4,
  724. (_, 3 | 6) => 9,
  725. (_, c) => {
  726. return Err(ShaderError::Unsupported {
  727. offset: 0,
  728. what: match c {
  729. 0 => "a signature element of unknown type",
  730. _ => "a 64-bit signature element",
  731. },
  732. });
  733. }
  734. };
  735. let register = u32_at(part, at + 20)?;
  736. out.push(container::SigElement {
  737. name: String::from_utf8_lossy(name).into_owned(),
  738. index: u32_at(part, at + 8)?,
  739. kind,
  740. comp,
  741. interp: 0,
  742. row: (register != u32::MAX).then_some(register),
  743. col: mask.trailing_zeros().min(3) as u8,
  744. cols: mask.count_ones().max(1) as u8,
  745. usage: 0,
  746. half: (4..=6).contains(&raw),
  747. });
  748. }
  749. Ok(out)
  750. }
  751. #[cfg(test)]
  752. mod tests {
  753. use super::bitcode::Attr;
  754. use super::lower::LOOP_LIMIT;
  755. use super::parse_loop_limit;
  756. #[test]
  757. fn the_clean_up_switch_parses_or_runs_every_pass() {
  758. let all = super::bitcode::opt::ALL;
  759. assert_eq!(parse_shader_opt(None), all);
  760. assert_eq!(parse_shader_opt(Some("0")), 0);
  761. assert_eq!(parse_shader_opt(Some(" 1 ")), 1);
  762. assert_eq!(parse_shader_opt(Some("0x1")), 1);
  763. assert_eq!(parse_shader_opt(Some("0xffffffff")), all);
  764. assert_eq!(parse_shader_opt(Some("on")), all);
  765. }
  766. #[test]
  767. fn the_loop_limit_switch_parses_or_falls_back() {
  768. assert_eq!(parse_loop_limit(None), LOOP_LIMIT);
  769. assert_eq!(parse_loop_limit(Some("4096")), 4096);
  770. assert_eq!(parse_loop_limit(Some(" 0x1000 ")), 4096);
  771. assert_eq!(parse_loop_limit(Some("1")), 1);
  772. for bad in ["", "0", "-5", "lots", "0x", "4294967296"] {
  773. assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}");
  774. }
  775. }
  776. use super::container::SigElement;
  777. use super::shader::Shader;
  778. use super::*;
  779. use crate::native::{ComputeIo, StageIo};
  780. /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`).
  781. /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose
  782. /// output signature has SV_StencilRef, and the feature bit
  783. /// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks
  784. /// both against the module.
  785. #[test]
  786. fn a_stencil_export_declares_the_stencil_ref_feature() {
  787. let words = [
  788. 0x7E00_02F2u32, // v_mov_b32 v0, 1.0
  789. 0x7E02_0285, // v_mov_b32 v1, 5
  790. 0xF800_1883,
  791. 0x0000_0100, // exp mrtz v0, v1, off, off done vm
  792. 0xBF81_0000,
  793. ];
  794. let native = NativeProgram {
  795. stage: HwStage::Ps,
  796. wave64: false,
  797. vgprs: 2,
  798. layout: vec![],
  799. used: vec![],
  800. io: StageIo::Ps {
  801. inputs: vec![],
  802. input_addr: 0,
  803. db_shader_control: 0,
  804. patches: vec![],
  805. },
  806. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  807. };
  808. let el = |name: &str, kind, comp| SigElement {
  809. name: name.into(),
  810. index: 0,
  811. kind,
  812. comp,
  813. interp: 0,
  814. row: None,
  815. col: 0,
  816. cols: 1,
  817. usage: 1,
  818. half: false,
  819. };
  820. let osg1 =
  821. container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false);
  822. let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
  823. let c = Container::parse(&bytes).unwrap();
  824. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  825. let st = structure::structure(&p).unwrap();
  826. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  827. let io = io::raise(&p, &native).unwrap();
  828. let out = emit(&c, &native, &p, &st, &io, &res).unwrap();
  829. // dxil.dll, where there is one, checks the flags against the module.
  830. #[cfg(windows)]
  831. if let Ok(mut v) = super::validator::Validator::load(
  832. super::validator::Validator::default_path().as_deref(),
  833. ) {
  834. v.validate(&mut out.dxil.clone()).unwrap();
  835. }
  836. let host = Container::parse(&out.dxil).unwrap();
  837. let sfi0 = host.part(FourCC::SFI0).unwrap().data;
  838. let features = u64::from_le_bytes(sfi0.try_into().unwrap());
  839. assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef");
  840. }
  841. /// A pixel program with an ordered section, as the console compiler
  842. /// makes one of rasterizer ordered views (the title's hair cards keep
  843. /// their nearest layers that way): the wait for overlapped waves is
  844. /// skipped, the views inside the section are the host's ordered ones,
  845. /// the one after it is not.
  846. #[test]
  847. fn an_ordered_section_uses_rasterizer_ordered_views() {
  848. let section = [
  849. 0xBE82_0300u32, // s_mov_b32 s2, s0
  850. 0xBE83_0380, // s_mov_b32 s3, 0
  851. 0xF40C_0201, // s_load_dwordx8 s[8:15], s[2:3], 0
  852. 0xFA00_0000,
  853. 0x9390_FF01, // s_bfe_u32 s16, s1, 0x2001c
  854. 0x0002_001C,
  855. 0x9391_FF01, // s_bfe_u32 s17, s1, 0xa0000
  856. 0x000A_0000,
  857. 0x8F10_8110, // s_lshl_b32 s16, s16, 1
  858. 0x9392_FF01, // s_bfe_u32 s18, s1, 0xa0010
  859. 0x000A_0010,
  860. 0xBE91_0711, // s_not_b32 s17, s17
  861. 0x9013_9F01, // s_lshr_b32 s19, s1, 31
  862. 0x8810_8110, // s_or_b32 s16, s16, 1
  863. 0x8112_1112, // s_add_i32 s18, s18, s17
  864. 0xBF06_8013, // s_cmp_eq_u32 s19, 0
  865. 0xB990_1019, // s_setreg_b32 hwreg(HW_REG_POPS_PACKER, 0, 3), s16
  866. 0x8514_807E, // s_cselect_b32 s20, exec_lo, 0
  867. 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17
  868. 0xBF08_1215, // s_cmp_gt_u32 s21, s18
  869. 0x8516_807E, // s_cselect_b32 s22, exec_lo, 0
  870. 0x8814_1614, // s_or_b32 s20, s20, s22
  871. 0x876A_147E, // s_and_b32 vcc_lo, exec_lo, s20
  872. 0xBF87_0004, // s_cbranch_vccnz past the wait
  873. 0xBF8E_FFFF, // s_sleep 0xffff
  874. 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17
  875. 0xBF0A_1512, // s_cmp_lt_u32 s18, s21
  876. 0xBF84_FFFC, // s_cbranch_scc0 back to the sleep
  877. 0x7E00_0280, // v_mov_b32 v0, 0
  878. 0x7E02_0280, // v_mov_b32 v1, 0
  879. 0xF000_3F88, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc dlc
  880. 0x0002_0200,
  881. 0x0604_04F2, // v_add_f32 v2, 1.0, v2
  882. 0xF020_3F08, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc
  883. 0x0002_0200,
  884. 0xBEFC_0380, // s_mov_b32 m0, 0
  885. 0xBF90_0007, // s_sendmsg sendmsg(MSG_ORDERED_PS_DONE)
  886. ];
  887. let end = [
  888. 0xF800_180Fu32, // exp mrt0 v2, v2, v2, v2 done vm
  889. 0x0202_0202,
  890. 0xBF81_0000, // s_endpgm
  891. ];
  892. // A store after the section, through an ordinary view.
  893. let after = [0xF020_3F08u32, 0x0002_0200];
  894. let lower = |words: Vec<u32>| {
  895. let native = NativeProgram {
  896. stage: HwStage::Ps,
  897. wave64: false,
  898. vgprs: 8,
  899. layout: vec![crate::native::RootParam {
  900. root: RootType::Table,
  901. table_offset_dwords: 0,
  902. sgprs: 1,
  903. base_register: 0,
  904. user_data: 0,
  905. slot: 0,
  906. }],
  907. used: vec![crate::native::UsedResource {
  908. kind: crate::native::ResourceType::Uav,
  909. root: RootType::Table,
  910. table_offset_dwords: 0,
  911. lower_bound: 0,
  912. stride: 4,
  913. dwords: 8,
  914. user_data: 0,
  915. slot: 0,
  916. }],
  917. io: StageIo::Ps {
  918. inputs: vec![],
  919. input_addr: 0,
  920. db_shader_control: 0,
  921. patches: vec![],
  922. },
  923. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  924. };
  925. let target = SigElement {
  926. name: "SV_Target".into(),
  927. index: 0,
  928. kind: 16,
  929. comp: 9,
  930. interp: 0,
  931. row: Some(0),
  932. col: 0,
  933. cols: 4,
  934. usage: 15,
  935. half: false,
  936. };
  937. let osg1 = container::signature(&[target], false);
  938. let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
  939. let c = Container::parse(&bytes).unwrap();
  940. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  941. let st = structure::structure(&p)?;
  942. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  943. let io = io::raise(&p, &native)?;
  944. let out = emit(&c, &native, &p, &st, &io, &res)?;
  945. #[cfg(windows)]
  946. if let Ok(mut v) = super::validator::Validator::load(
  947. super::validator::Validator::default_path().as_deref(),
  948. ) {
  949. v.validate(&mut out.dxil.clone()).unwrap();
  950. }
  951. let host = Container::parse(&out.dxil).unwrap();
  952. let sfi0 = host.part(FourCC::SFI0).unwrap().data;
  953. Ok::<u64, ShaderError>(u64::from_le_bytes(sfi0.try_into().unwrap()))
  954. };
  955. // D3D_SHADER_REQUIRES_ROVS
  956. let features = lower([&section[..], &end].concat()).unwrap();
  957. assert_ne!(features & 0x1000, 0, "SFI0 {features:#x}: no ROVs");
  958. lower([&section[..], &after, &end].concat()).unwrap();
  959. // The same accesses outside a section: ordinary views, no feature.
  960. let plain = [&section[..4], &section[28..35], &end].concat();
  961. let features = lower(plain).unwrap();
  962. assert_eq!(features & 0x1000, 0, "SFI0 {features:#x}: ROVs");
  963. // Without the section's start the wait stays unknown.
  964. let mut unmarked = [&section[..], &end].concat();
  965. unmarked.remove(16);
  966. assert!(lower(unmarked).is_err());
  967. }
  968. /// A wave64 compute program that writes only EXEC's high dword
  969. /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was
  970. /// opaque and keyed by the unchanged low dword, so building its lane bit
  971. /// needed the mask's own value: lowering recursed until the stack
  972. /// overflowed, which takes the whole process down (found by
  973. /// random-input testing). Now that low dword, seen with two high
  974. /// dwords, has no mask, and the instruction fails like any other that
  975. /// cannot be expressed: its result is missing, and only a side effect
  976. /// that uses it would stop the translation.
  977. #[test]
  978. fn an_exec_high_write_does_not_overflow_the_stack() {
  979. // s_mov_b32 exec_hi, 0; v_mov_b32 v1, v0; s_endpgm
  980. let words = [0xBEFF_0380u32, 0x7E02_0300, 0xBF81_0000];
  981. let native = NativeProgram {
  982. stage: HwStage::Cs,
  983. wave64: true,
  984. vgprs: 2,
  985. layout: vec![],
  986. used: vec![],
  987. io: StageIo::Cs(ComputeIo {
  988. rsrc2: 0,
  989. threads: [64, 1, 1],
  990. }),
  991. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  992. };
  993. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  994. let st = structure::structure(&p).unwrap();
  995. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  996. let io = io::raise(&p, &native).unwrap();
  997. let container = crate::dxbc::build(&[]);
  998. let c = Container::parse(&container).unwrap();
  999. if let Err(e) = emit(&c, &native, &p, &st, &io, &res) {
  1000. assert!(e.to_string().contains("its own value"), "{e}");
  1001. }
  1002. }
  1003. /// A wave64 compute program: `body`, then a store of v1 to a UAV.
  1004. fn stores_v1(body: &[u32]) -> Result<(), ShaderError> {
  1005. use crate::native::RootParam;
  1006. use crate::{ResourceType, RootType, UsedResource};
  1007. // s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0
  1008. let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000];
  1009. words.extend_from_slice(body);
  1010. // v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen;
  1011. // s_endpgm
  1012. words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]);
  1013. let native = NativeProgram {
  1014. stage: HwStage::Cs,
  1015. wave64: true,
  1016. vgprs: 4,
  1017. layout: vec![RootParam {
  1018. root: RootType::Table,
  1019. table_offset_dwords: 0,
  1020. sgprs: 1,
  1021. base_register: 0,
  1022. user_data: 0,
  1023. slot: 0,
  1024. }],
  1025. used: vec![UsedResource {
  1026. kind: ResourceType::Uav,
  1027. root: RootType::Table,
  1028. table_offset_dwords: 0,
  1029. lower_bound: 0,
  1030. stride: 0,
  1031. dwords: 4,
  1032. user_data: 0,
  1033. slot: 0,
  1034. }],
  1035. io: StageIo::Cs(ComputeIo {
  1036. rsrc2: 2,
  1037. threads: [64, 1, 1],
  1038. }),
  1039. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1040. };
  1041. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1042. let res = resource::track(&p, &native.layout, native.stage, None).unwrap();
  1043. let io = io::raise(&p, &native).unwrap();
  1044. let st = structure::structure(&p).unwrap();
  1045. let container = crate::dxbc::build(&[]);
  1046. let c = Container::parse(&container).unwrap();
  1047. emit(&c, &native, &p, &st, &io, &res).map(|_| ())
  1048. }
  1049. /// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi`
  1050. /// or `exec_hi`): lanes 32-63 took the mask the low dword was first
  1051. /// written with (the compare's, EXEC's on entry). Now the store refuses;
  1052. /// without the write it translates.
  1053. #[test]
  1054. fn a_mask_whose_high_dword_is_rewritten_is_refused() {
  1055. // v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc
  1056. let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480];
  1057. // The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc.
  1058. let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480];
  1059. // v_mov_b32 v1, 7
  1060. let mov = [0x7E02_0287];
  1061. for body in [&select[..], &carry, &mov] {
  1062. stores_v1(body).unwrap();
  1063. }
  1064. // s_mov_b32 vcc_hi, 0 after the compare.
  1065. let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480];
  1066. let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480];
  1067. // s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after
  1068. // s_mov_b64 s[2:3], exec.
  1069. let exec_hi = [0xBEFF_0380, 0x7E02_0287];
  1070. let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287];
  1071. for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] {
  1072. assert!(stores_v1(body).is_err(), "{body:x?}");
  1073. }
  1074. }
  1075. /// `ds_bpermute_b32` stores nothing: each lane reads the lane its address
  1076. /// names. It stopped as "LDS the program does not allocate" (sticky lips)
  1077. /// or "an LDS operation" (the checkerboard shadow masks).
  1078. #[test]
  1079. fn a_backward_permute_reads_the_lane_its_address_names() {
  1080. // v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2
  1081. stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap();
  1082. }
  1083. /// A carry-in reading a join of compares after a divergent branch. A
  1084. /// lane that skipped the inner compare has VCC clear there (VOPC clears
  1085. /// inactive lanes), not the first compare's bit, so the join is no
  1086. /// per-lane phi: lowering refuses it.
  1087. #[test]
  1088. fn a_carry_in_from_a_divergent_join_is_refused() {
  1089. let body = [
  1090. 0x7E04_028B, // v_mov_b32 v2, 11
  1091. 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
  1092. 0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc
  1093. 0xBF88_0001, // s_cbranch_execz 1
  1094. 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0
  1095. 0x88FE_027E, // s_or_b64 exec, exec, s[2:3]
  1096. 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc
  1097. ];
  1098. let e = stores_v1(&body).unwrap_err().to_string();
  1099. assert!(e.contains("a carry-in from an untracked mask"), "{e}");
  1100. }
  1101. /// A pixel shader writing a constant colour.
  1102. #[cfg(windows)]
  1103. fn constant_color() -> Vec<u8> {
  1104. let mut s = Shader::new(true);
  1105. s.outputs.push(SigElement {
  1106. name: "SV_Target".into(),
  1107. index: 0,
  1108. kind: 16,
  1109. comp: 9,
  1110. interp: 0,
  1111. row: Some(0),
  1112. col: 0,
  1113. cols: 4,
  1114. usage: 15,
  1115. half: false,
  1116. });
  1117. let b = s.entry;
  1118. for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() {
  1119. let args = [
  1120. s.m.i32(0),
  1121. s.m.i32(0),
  1122. s.m.i8(c as u8),
  1123. s.m.f32(v.to_bits()),
  1124. ];
  1125. s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
  1126. }
  1127. s.m.terminate(b, super::bitcode::Term::Ret);
  1128. s.finish()
  1129. }
  1130. #[test]
  1131. #[cfg(windows)]
  1132. fn stub_pipeline_is_created() {
  1133. let Ok(host) = super::host::Host::new(false) else {
  1134. eprintln!("no SM 6.6 device; skipped");
  1135. return;
  1136. };
  1137. let ps = super::HostShader {
  1138. stage: crate::HwStage::Ps,
  1139. dxil: constant_color(),
  1140. user_data: Vec::new(),
  1141. samplers: Vec::new(),
  1142. static_samplers: Vec::new(),
  1143. root_cbvs: Vec::new(),
  1144. root_srvs: Vec::new(),
  1145. root_uavs: Vec::new(),
  1146. root_indexed_views: Vec::new(),
  1147. };
  1148. let file = |var: &str, stage| {
  1149. std::env::var(var).ok().map(|p| super::HostShader {
  1150. stage,
  1151. dxil: std::fs::read(p).unwrap(),
  1152. user_data: Vec::new(),
  1153. samplers: Vec::new(),
  1154. static_samplers: Vec::new(),
  1155. root_cbvs: Vec::new(),
  1156. root_srvs: Vec::new(),
  1157. root_uavs: Vec::new(),
  1158. root_indexed_views: Vec::new(),
  1159. })
  1160. };
  1161. let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
  1162. let vs = file("VICTORY_REF_VS", crate::HwStage::Vs)
  1163. .unwrap_or_else(|| super::host::stub_vs(&ps).unwrap());
  1164. if let Ok(mut v) = super::validator::Validator::load(
  1165. super::validator::Validator::default_path().as_deref(),
  1166. ) {
  1167. v.validate(&mut vs.dxil.clone()).unwrap();
  1168. }
  1169. host.pipeline(&vs, &ps).unwrap();
  1170. // The runtime checks the container hash: no hash or a wrong one is
  1171. // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass
  1172. // value; ours works with older ones too.)
  1173. let mut wrong = ps.dxil[4..20].to_vec();
  1174. wrong[0] ^= 1;
  1175. for digest in [&[0u8; 16][..], &wrong] {
  1176. let mut other = ps.clone();
  1177. other.dxil[4..20].copy_from_slice(digest);
  1178. assert!(
  1179. host.pipeline(&vs, &other).is_err(),
  1180. "digest {digest:02x?} accepted"
  1181. );
  1182. }
  1183. }
  1184. #[test]
  1185. #[cfg(windows)]
  1186. fn constant_color_validates() {
  1187. let mut c = constant_color();
  1188. let path = super::validator::Validator::default_path();
  1189. let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else {
  1190. eprintln!("no dxil.dll; skipped");
  1191. return;
  1192. };
  1193. let ours = c[4..20].to_vec();
  1194. v.validate(&mut c).unwrap();
  1195. assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
  1196. }
  1197. /// A pixel shader interpolating at sample positions (PERSP_SAMPLE
  1198. /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency:
  1199. /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1)
  1200. /// whenever an input is interpolated per sample.
  1201. #[test]
  1202. fn sample_interpolated_inputs_set_psv_sample_frequency() {
  1203. let words = [
  1204. 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x
  1205. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1206. 0xF800_180F,
  1207. 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm
  1208. 0xBF81_0000,
  1209. ];
  1210. let psv_of = |input_addr: u32| {
  1211. let native = super::NativeProgram {
  1212. stage: super::HwStage::Ps,
  1213. wave64: false,
  1214. vgprs: 4,
  1215. layout: vec![],
  1216. used: vec![],
  1217. io: crate::native::StageIo::Ps {
  1218. inputs: vec![crate::native::PsInput {
  1219. usage: crate::native::Usage::Generic,
  1220. row: 0,
  1221. mask: 0b1111,
  1222. attr: 0,
  1223. flat: false,
  1224. fp16: false,
  1225. pack2: false,
  1226. row2: 0,
  1227. }],
  1228. input_addr,
  1229. db_shader_control: 0,
  1230. patches: vec![],
  1231. },
  1232. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1233. };
  1234. let el = |name: &str, kind, usage| SigElement {
  1235. name: name.into(),
  1236. index: 0,
  1237. kind,
  1238. comp: 9,
  1239. interp: 0,
  1240. row: Some(0),
  1241. col: 0,
  1242. cols: 4,
  1243. usage,
  1244. half: false,
  1245. };
  1246. let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true);
  1247. let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false);
  1248. let bytes =
  1249. crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]);
  1250. let c = super::Container::parse(&bytes).unwrap();
  1251. let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1252. let st = crate::structure::structure(&p).unwrap();
  1253. let res =
  1254. crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1255. let io = crate::io::raise(&p, &native).unwrap();
  1256. let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap();
  1257. // dxil.dll, where there is one, checks PSV0 against the module.
  1258. #[cfg(windows)]
  1259. if let Ok(mut v) = super::validator::Validator::load(
  1260. super::validator::Validator::default_path().as_deref(),
  1261. ) {
  1262. v.validate(&mut out.dxil.clone()).unwrap();
  1263. }
  1264. let host = super::Container::parse(&out.dxil).unwrap();
  1265. host.part(super::FourCC::PSV0).unwrap().data.to_vec()
  1266. };
  1267. // Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}.
  1268. let center = psv_of(1 << 1);
  1269. assert_eq!(center[4 + 1], 0, "center interpolation is per pixel");
  1270. let sample = psv_of(1 << 0);
  1271. assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency");
  1272. }
  1273. /// A pixel shader reading channel z of an input whose element starts at
  1274. /// w. Looking the channel up subtracted the element's first channel
  1275. /// before checking the channel lies in it, so in a build with overflow
  1276. /// checks (tests, debug) any read below an element that starts at z or
  1277. /// w panicked, whichever row it was in (found by random-input testing).
  1278. #[test]
  1279. fn reading_a_channel_below_an_input_element_does_not_underflow() {
  1280. // v_interp_mov_f32 v3, p0, attr0.z; s_endpgm
  1281. let words = [0xC80E_0202u32, 0xBF81_0000];
  1282. let native = super::NativeProgram {
  1283. stage: super::HwStage::Ps,
  1284. wave64: false,
  1285. vgprs: 4,
  1286. layout: vec![],
  1287. used: vec![],
  1288. io: crate::native::StageIo::Ps {
  1289. inputs: vec![crate::native::PsInput {
  1290. usage: crate::native::Usage::Generic,
  1291. row: 0,
  1292. mask: 0b1000,
  1293. attr: 0,
  1294. flat: false,
  1295. fp16: false,
  1296. pack2: false,
  1297. row2: 0,
  1298. }],
  1299. input_addr: 0,
  1300. db_shader_control: 0,
  1301. patches: vec![],
  1302. },
  1303. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1304. };
  1305. let w_only = SigElement {
  1306. name: "TEXCOORD".into(),
  1307. index: 0,
  1308. kind: 0,
  1309. comp: 9,
  1310. interp: 0,
  1311. row: Some(0),
  1312. col: 3,
  1313. cols: 1,
  1314. usage: 0,
  1315. half: false,
  1316. };
  1317. let isg1 = super::container::signature(&[w_only], true);
  1318. let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]);
  1319. let c = super::Container::parse(&bytes).unwrap();
  1320. let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  1321. let st = crate::structure::structure(&p).unwrap();
  1322. let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  1323. let io = crate::io::raise(&p, &native).unwrap();
  1324. // Translated or refused with a reason; it must not panic.
  1325. let _ = super::emit(&c, &native, &p, &st, &io, &res);
  1326. }
  1327. #[test]
  1328. fn valu_div_f32_sequence_executes_on_gpu() {
  1329. let words: &[u32] = &[
  1330. 0xBE85_0380, // s_mov_b32 s5, 0
  1331. 0xF408_0202,
  1332. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
  1333. 0xF408_0302,
  1334. 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
  1335. 0x340E_0083, // v_lshlrev_b32 v7, 3, v0
  1336. 0xE034_1000,
  1337. 0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen
  1338. 0xD56D_6A03,
  1339. 0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1
  1340. 0xD56D_1008,
  1341. 0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1
  1342. 0x7E08_5503, // v_rcp_f32 v4, v3
  1343. 0xD54B_0005,
  1344. 0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0
  1345. 0xD54B_0004,
  1346. 0x0412_0905, // v_fma_f32 v4, v5, v4, v4
  1347. 0x100A_0908, // v_mul_f32 v5, v8, v4
  1348. 0xD54B_0006,
  1349. 0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8
  1350. 0xD56F_0004,
  1351. 0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5
  1352. 0xD55F_0001,
  1353. 0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1
  1354. 0x340E_0082, // v_lshlrev_b32 v7, 2, v0
  1355. 0xE070_1000,
  1356. 0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen
  1357. 0xBF81_0000, // s_endpgm
  1358. ];
  1359. let native = super::NativeProgram {
  1360. stage: super::HwStage::Cs,
  1361. wave64: false,
  1362. vgprs: 9,
  1363. layout: vec![
  1364. crate::RootParam {
  1365. root: crate::RootType::Constants,
  1366. table_offset_dwords: 0,
  1367. sgprs: 4,
  1368. base_register: 0,
  1369. user_data: 0,
  1370. slot: 0,
  1371. },
  1372. crate::RootParam {
  1373. root: crate::RootType::Table,
  1374. table_offset_dwords: 0,
  1375. sgprs: 1,
  1376. base_register: 0,
  1377. user_data: 4,
  1378. slot: 1,
  1379. },
  1380. ],
  1381. used: vec![
  1382. crate::UsedResource {
  1383. kind: crate::ResourceType::Srv,
  1384. root: crate::RootType::Table,
  1385. table_offset_dwords: 0,
  1386. lower_bound: 0,
  1387. stride: 4,
  1388. dwords: 4,
  1389. user_data: 4,
  1390. slot: 1,
  1391. },
  1392. crate::UsedResource {
  1393. kind: crate::ResourceType::Uav,
  1394. root: crate::RootType::Table,
  1395. table_offset_dwords: 8,
  1396. lower_bound: 0,
  1397. stride: 4,
  1398. dwords: 4,
  1399. user_data: 4,
  1400. slot: 1,
  1401. },
  1402. ],
  1403. io: crate::native::StageIo::Cs(crate::native::ComputeIo {
  1404. rsrc2: 5 << 1,
  1405. threads: [7, 1, 1],
  1406. }),
  1407. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1408. };
  1409. let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap();
  1410. let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap();
  1411. let io = crate::io::raise(&p, &native).unwrap();
  1412. let st = crate::structure::structure(&p).unwrap();
  1413. let l = super::lower::lower(&super::lower::Parts {
  1414. native: &native,
  1415. p: &p,
  1416. st: &st,
  1417. io: &io,
  1418. res: &res,
  1419. inputs: Vec::new(),
  1420. outputs: Vec::new(),
  1421. prims: Vec::new(),
  1422. mesh_stride: 0,
  1423. })
  1424. .unwrap();
  1425. let mut dxil = l.dxil;
  1426. #[cfg(windows)]
  1427. if let Ok(mut v) = super::validator::Validator::load(
  1428. super::validator::Validator::default_path().as_deref(),
  1429. ) {
  1430. v.validate(&mut dxil).unwrap();
  1431. }
  1432. #[cfg(windows)]
  1433. if let Ok(host) = super::host::Host::new(false) {
  1434. let cs = super::HostShader {
  1435. stage: super::HwStage::Cs,
  1436. dxil,
  1437. user_data: l.user_data,
  1438. samplers: Vec::new(),
  1439. static_samplers: Vec::new(),
  1440. root_cbvs: l.root_cbvs,
  1441. root_srvs: l.root_srvs,
  1442. root_uavs: l.root_uavs,
  1443. root_indexed_views: Vec::new(),
  1444. };
  1445. let (root, pso) = host.compute_pipeline(&cs).unwrap();
  1446. let inputs: Vec<u32> = [
  1447. 7.0f32, 3.0, -1.0, 1e-40, 1.0, 1e35, 1e-35, 1e-36, 0.0, 0.0, -1.0, 0.0, -1e35, 1e35,
  1448. ]
  1449. .into_iter()
  1450. .map(f32::to_bits)
  1451. .collect();
  1452. let out = host
  1453. .dispatch(
  1454. &root,
  1455. &pso,
  1456. &super::host::Dispatch {
  1457. roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))],
  1458. views: &[
  1459. super::host::View::Buffer {
  1460. data: &inputs,
  1461. stride: super::host::Stride::Raw,
  1462. },
  1463. super::host::View::RawUav(64),
  1464. ],
  1465. samplers: &[],
  1466. groups: [1, 1, 1],
  1467. },
  1468. )
  1469. .unwrap();
  1470. let got: Vec<f32> = out[0][..7].iter().copied().map(f32::from_bits).collect();
  1471. assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got);
  1472. assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits());
  1473. assert!(
  1474. (got[2] - 1e-35).abs() <= 1e-40,
  1475. "lane 2 got {:?} ({:#x})",
  1476. got[2],
  1477. out[0][2]
  1478. );
  1479. assert!(
  1480. (got[3] - 10.0).abs() < 1e-5,
  1481. "lane 3 got {:?} ({:#x})",
  1482. got[3],
  1483. out[0][3]
  1484. );
  1485. assert_eq!(out[0][4], 0xFFC0_0000);
  1486. assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits());
  1487. assert!(
  1488. (got[6] - (-1.0)).abs() < 1e-6,
  1489. "lane 6 got {:?} ({:#x})",
  1490. got[6],
  1491. out[0][6]
  1492. );
  1493. }
  1494. }
  1495. }
  1496. #[cfg(test)]
  1497. mod atomic_tests {
  1498. use super::*;
  1499. use crate::native::{ComputeIo, RootParam, StageIo};
  1500. #[test]
  1501. fn heap_texture_atomic_widths() {
  1502. // A synthetic compute shader loads a 2D UAV from a root table,
  1503. // compares or adds at (0, 0), then uses the returned register(s).
  1504. for (opcode, mask, wide) in [
  1505. (16u32, 3, false),
  1506. (16, 15, true),
  1507. (17, 1, false),
  1508. (17, 3, true),
  1509. ] {
  1510. let words = [
  1511. 0xBE81_0380, // s_mov_b32 s1, 0 (table address high)
  1512. 0xF40C_0200,
  1513. 0xFA00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0
  1514. 0x7E00_0280,
  1515. 0x7E02_0280, // v0, v1 = coordinates
  1516. 0x7E04_0281,
  1517. 0x7E06_0282,
  1518. 0x7E08_0283,
  1519. 0x7E0A_0284, // v2..v5 = 1..4
  1520. 0xF000_2008 | opcode << 18 | mask << 8,
  1521. 0x0002_0200,
  1522. // Use the old value in a second atomic at the same location.
  1523. 0xF044_0008 | (if wide { 3 } else { 1 }) << 8,
  1524. 0x0002_0200,
  1525. 0xBF81_0000,
  1526. ];
  1527. let native = NativeProgram {
  1528. stage: HwStage::Cs,
  1529. wave64: false,
  1530. vgprs: 6,
  1531. layout: vec![RootParam {
  1532. root: RootType::Table,
  1533. table_offset_dwords: 0,
  1534. sgprs: 1,
  1535. base_register: 0,
  1536. user_data: 0,
  1537. slot: 0,
  1538. }],
  1539. used: vec![],
  1540. io: StageIo::Cs(ComputeIo {
  1541. rsrc2: 2,
  1542. threads: [32, 1, 1],
  1543. }),
  1544. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1545. };
  1546. let p = ir::build(&native.code, false, native.vgprs).unwrap();
  1547. let bytes = crate::dxbc::build(&[]);
  1548. let shader = emit(
  1549. &Container::parse(&bytes).unwrap(),
  1550. &native,
  1551. &p,
  1552. &structure::structure(&p).unwrap(),
  1553. &io::raise(&p, &native).unwrap(),
  1554. &resource::track(&p, &native.layout, native.stage, None).unwrap(),
  1555. )
  1556. .unwrap();
  1557. let container = Container::parse(&shader.dxil).unwrap();
  1558. let features = u64::from_le_bytes(
  1559. container
  1560. .part(FourCC::SFI0)
  1561. .unwrap()
  1562. .data
  1563. .try_into()
  1564. .unwrap(),
  1565. );
  1566. let required = 0x1040_8000; // heap atomics, typed atomics, Int64Ops
  1567. assert_eq!(features & required, if wide { required } else { 0 });
  1568. #[cfg(windows)]
  1569. if let Ok(mut v) =
  1570. validator::Validator::load(validator::Validator::default_path().as_deref())
  1571. {
  1572. v.validate(&mut shader.dxil.clone()).unwrap();
  1573. }
  1574. }
  1575. }
  1576. }
  1577. #[cfg(test)]
  1578. mod barycentric_tests {
  1579. use super::container::SigElement;
  1580. use super::*;
  1581. use crate::native::{PsInput, StageIo, Usage};
  1582. /// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER.
  1583. const PERSP_CENTER: u32 = 1 << 1;
  1584. const LINEAR_CENTER: u32 = 1 << 5;
  1585. /// `exp mrt0, v<r>, v<r>, v<r>, v<r> done vm`.
  1586. fn exp_mrt0(r: u32) -> [u32; 2] {
  1587. [0xF800_180F, r * 0x0101_0101]
  1588. }
  1589. /// VOP2 `v_add_f32 v<dst>, v<a>, v<b>`.
  1590. fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 {
  1591. 3 << 25 | dst << 17 | b << 9 | (256 + a)
  1592. }
  1593. fn element(name: &str, kind: u8, row: u32) -> SigElement {
  1594. SigElement {
  1595. name: name.into(),
  1596. index: 0,
  1597. kind,
  1598. comp: 9,
  1599. interp: 0,
  1600. row: Some(row),
  1601. col: 0,
  1602. cols: 4,
  1603. usage: 0,
  1604. half: false,
  1605. }
  1606. }
  1607. /// Translates a pixel program with the input VGPRs `input_addr`
  1608. /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0).
  1609. fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> {
  1610. let native = NativeProgram {
  1611. stage: HwStage::Ps,
  1612. wave64: false,
  1613. vgprs: 8,
  1614. layout: vec![],
  1615. used: vec![],
  1616. io: StageIo::Ps {
  1617. inputs: vec![PsInput {
  1618. usage: Usage::Generic,
  1619. row: 0,
  1620. mask: 0b1111,
  1621. attr: 0,
  1622. flat: false,
  1623. fp16: false,
  1624. pack2: false,
  1625. row2: 0,
  1626. }],
  1627. input_addr,
  1628. db_shader_control: 0,
  1629. patches: vec![],
  1630. },
  1631. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  1632. };
  1633. let mut target = element("SV_Target", 16, 0);
  1634. target.usage = 15;
  1635. let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true);
  1636. let osg1 = container::signature(&[target], false);
  1637. let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]);
  1638. let c = Container::parse(&bytes).unwrap();
  1639. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  1640. let res = resource::track(&p, &native.layout, native.stage, None)?;
  1641. let io = io::raise(&p, &native)?;
  1642. let st = structure::structure(&p)?;
  1643. emit(&c, &native, &p, &st, &io, &res)
  1644. }
  1645. /// A pixel program's first-lane loop (no table entry in it, so not a waterfall the tracker
  1646. /// knows) asks for helper lanes, which is valid DXIL (upstream #946's program).
  1647. #[test]
  1648. fn a_pixel_first_lane_loop_serves_helper_lanes() {
  1649. let shader = pixel(
  1650. &[
  1651. 0xD765_0000, 0x0001_00C1, // v_mbcnt_lo_u32_b32 v0, -1, 0
  1652. 0x7E02_0280, // v_mov_b32 v1, 0
  1653. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  1654. 0x7E18_0500, // v_readfirstlane_b32 s12, v0
  1655. 0x7D84_000C, // v_cmp_eq_u32 vcc, s12, v0
  1656. 0xBE95_3C6A, // s_and_saveexec_b32 s21, vcc_lo
  1657. 0xBF80_0000, // s_nop 0
  1658. 0x7E02_02FF, 0x3F80_0000, // v_mov_b32 v1, 1.0
  1659. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  1660. 0xBF89_FFF8, // s_cbranch_execnz loop
  1661. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  1662. 0xF800_180F, 0x0101_0101, // exp mrt0 v1 v1 v1 v1 done vm
  1663. 0xBF81_0000, // s_endpgm
  1664. ],
  1665. 0,
  1666. )
  1667. .unwrap();
  1668. validate(&shader);
  1669. }
  1670. /// The translation's `SFI0` features and `ISG1` rows.
  1671. fn parts(shader: &HostShader) -> (u64, Vec<SigElement>) {
  1672. let c = Container::parse(&shader.dxil).unwrap();
  1673. let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap();
  1674. (
  1675. u64::from_le_bytes(sfi0),
  1676. signature(c.part(FourCC::ISG1).unwrap().data).unwrap(),
  1677. )
  1678. }
  1679. fn validate(shader: &HostShader) {
  1680. #[cfg(windows)]
  1681. if let Ok(mut v) =
  1682. validator::Validator::load(validator::Validator::default_path().as_deref())
  1683. {
  1684. v.validate(&mut shader.dxil.clone()).unwrap();
  1685. }
  1686. let _ = shader;
  1687. }
  1688. /// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as
  1689. /// plain floats: they are channels y and z of `SV_Barycentrics`, the
  1690. /// weights of vertices 1 and 2.
  1691. #[test]
  1692. fn barycentrics_read_as_values_are_sv_barycentrics() {
  1693. let [e0, e1] = exp_mrt0(2);
  1694. let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000];
  1695. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1696. let (features, inputs) = parts(&shader);
  1697. assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
  1698. let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect();
  1699. assert_eq!(bary.len(), 1, "{inputs:?}");
  1700. assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3));
  1701. // Not packed: the validator wants packing location -1.
  1702. assert_eq!(bary[0].row, None);
  1703. // Only y and z (I and J) are read.
  1704. let isg1 = Container::parse(&shader.dxil).unwrap();
  1705. let isg1 = isg1.part(FourCC::ISG1).unwrap().data;
  1706. let rw: Vec<u8> = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect();
  1707. assert!(rw.contains(&0b110), "{rw:?}");
  1708. validate(&shader);
  1709. }
  1710. /// Two kinds of barycentrics read directly: one element per mode.
  1711. #[test]
  1712. fn two_barycentric_modes_get_two_elements() {
  1713. // v0-v1 perspective i, j; v2-v3 linear i, j.
  1714. let [e0, e1] = exp_mrt0(4);
  1715. let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000];
  1716. let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap();
  1717. let (_, inputs) = parts(&shader);
  1718. let mut indices: Vec<u32> = inputs
  1719. .iter()
  1720. .filter(|e| e.kind == 28)
  1721. .map(|e| e.index)
  1722. .collect();
  1723. indices.sort();
  1724. assert_eq!(indices, [0, 1], "{inputs:?}");
  1725. validate(&shader);
  1726. }
  1727. /// I and J only fed to `v_interp_*` stay host interpolation: no
  1728. /// barycentrics are declared.
  1729. #[test]
  1730. fn interpolation_alone_declares_no_barycentrics() {
  1731. let [e0, e1] = exp_mrt0(2);
  1732. let words = [
  1733. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  1734. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1735. e0,
  1736. e1,
  1737. 0xBF81_0000,
  1738. ];
  1739. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1740. let (features, inputs) = parts(&shader);
  1741. assert_eq!(features & 0x2_0000, 0);
  1742. assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
  1743. validate(&shader);
  1744. }
  1745. #[test]
  1746. fn a_standalone_first_half_reads_the_vertices() {
  1747. let shader = first_half_pixel(false);
  1748. let (_, inputs) = parts(&shader);
  1749. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  1750. assert_eq!(texcoord_mode(&shader), 1);
  1751. validate(&shader);
  1752. }
  1753. #[test]
  1754. fn a_first_half_read_beside_its_pair_keeps_its_partial_value() {
  1755. let shader = first_half_pixel(true);
  1756. assert_eq!(texcoord_mode(&shader), 1);
  1757. validate(&shader);
  1758. }
  1759. fn first_half_pixel(paired: bool) -> HostShader {
  1760. let [e0, e1] = exp_mrt0(2);
  1761. let mut words = vec![0xC808_0000]; // v_interp_p1_f32 v2, v0, attr0.x
  1762. if paired {
  1763. words.extend([
  1764. 0x7E06_0302, // v_mov_b32 v3, v2 (keep the partial value)
  1765. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1766. v_add_f32(2, 2, 3),
  1767. ]);
  1768. }
  1769. words.extend([e0, e1, 0xBF81_0000]);
  1770. pixel(&words, PERSP_CENTER).unwrap()
  1771. }
  1772. #[test]
  1773. #[cfg(windows)]
  1774. fn first_half_values_render_on_hardware_and_warp() {
  1775. use super::bitcode::{Attr, Term};
  1776. use super::host::{Draw, Host};
  1777. use super::shader::Shader;
  1778. let _one = super::valu_tests::ONE_AT_A_TIME
  1779. .lock()
  1780. .unwrap_or_else(|e| e.into_inner());
  1781. // Pass POSITION and TEXCOORD through, with TEXCOORD in the same
  1782. // output row as the translated pixel shader's input signature.
  1783. let mut s = Shader::new(false);
  1784. s.inputs = vec![element("POSITION", 0, 0), element("TEXCOORD", 0, 1)];
  1785. for e in &mut s.inputs {
  1786. e.usage = 15;
  1787. }
  1788. s.outputs = vec![element("TEXCOORD", 0, 0), element("SV_Position", 3, 1)];
  1789. for (i, e) in s.outputs.iter_mut().enumerate() {
  1790. e.usage = 15;
  1791. e.interp = if i == 1 { 4 } else { 2 };
  1792. }
  1793. for row in 0..2 {
  1794. for col in 0..4 {
  1795. let args = [s.m.i32(row), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)];
  1796. let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args);
  1797. let args = [s.m.i32(1 - row), s.m.i32(0), s.m.i8(col), v];
  1798. s.op(
  1799. s.entry,
  1800. "storeOutput.f32",
  1801. Attr::NoUnwind,
  1802. s.t.void,
  1803. 5,
  1804. &args,
  1805. );
  1806. }
  1807. }
  1808. s.m.terminate(s.entry, Term::Ret);
  1809. let vs = HostShader {
  1810. stage: HwStage::Vs,
  1811. dxil: s.finish(),
  1812. user_data: Vec::new(),
  1813. samplers: Vec::new(),
  1814. static_samplers: Vec::new(),
  1815. root_cbvs: Vec::new(),
  1816. root_srvs: Vec::new(),
  1817. root_uavs: Vec::new(),
  1818. root_indexed_views: Vec::new(),
  1819. };
  1820. validate(&vs);
  1821. // One triangle covers an 8x8 target, with attribute values 2, 6, 10.
  1822. let vertices = [
  1823. -1.0, 1.0, 0.5, 1.0, 2.0, 0.0, 0.0, 0.0, -1.0, -3.0, 0.5, 1.0, 6.0, 0.0, 0.0, 0.0, 3.0,
  1824. 1.0, 0.5, 1.0, 10.0, 0.0, 0.0, 0.0,
  1825. ];
  1826. let mut ran = 0;
  1827. for (backend, warp) in [("hardware", false), ("WARP", true)] {
  1828. let Ok(host) = Host::new(warp) else { continue };
  1829. let mut options =
  1830. windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS3::default();
  1831. // SAFETY: a correctly sized output for the feature query.
  1832. unsafe {
  1833. host.device
  1834. .CheckFeatureSupport(
  1835. windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_D3D12_OPTIONS3,
  1836. (&raw mut options).cast(),
  1837. size_of_val(&options) as u32,
  1838. )
  1839. .unwrap();
  1840. }
  1841. if !options.BarycentricsSupported.as_bool() {
  1842. eprintln!("no barycentrics on {backend}; skipped");
  1843. continue;
  1844. }
  1845. for paired in [false, true] {
  1846. let ps = first_half_pixel(paired);
  1847. validate(&ps);
  1848. let (root, pso) = host.pipeline(&vs, &ps).expect("interpolation pipeline");
  1849. let out = host
  1850. .draw(
  1851. &root,
  1852. &pso,
  1853. &Draw {
  1854. roots: Vec::new(),
  1855. textures: &[],
  1856. samplers: &[],
  1857. vertices: &vertices,
  1858. stride: 32,
  1859. size: (8, 8),
  1860. mesh_groups: 0,
  1861. },
  1862. )
  1863. .expect("draw partial interpolation");
  1864. for (n, texel) in out.iter().enumerate() {
  1865. let i = (n / 8) as f32 / 16.0 + 0.5 / 16.0;
  1866. let j = (n % 8) as f32 / 16.0 + 0.5 / 16.0;
  1867. let partial = 2.0 + i * 4.0;
  1868. let want = if paired {
  1869. partial + 2.0 + i * 4.0 + j * 8.0
  1870. } else {
  1871. partial
  1872. };
  1873. for &got in texel {
  1874. assert!(
  1875. (got - want).abs() < 1e-5,
  1876. "{backend} paired={paired} pixel={n}: got {got}, want {want}"
  1877. );
  1878. }
  1879. }
  1880. }
  1881. ran += 1;
  1882. eprintln!("partial interpolation renders correctly on {backend}");
  1883. }
  1884. if ran == 0 {
  1885. eprintln!("no SM 6.6 host with barycentrics; GPU checks skipped");
  1886. }
  1887. }
  1888. /// Both: the attribute is interpolated and J is used as a value.
  1889. #[test]
  1890. fn interpolation_and_a_barycentric_value_together() {
  1891. let [e0, e1] = exp_mrt0(3);
  1892. let words = [
  1893. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  1894. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1895. v_add_f32(3, 2, 1), // v3 = attribute + j
  1896. e0,
  1897. e1,
  1898. 0xBF81_0000,
  1899. ];
  1900. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1901. let (features, inputs) = parts(&shader);
  1902. assert_ne!(features & 0x2_0000, 0);
  1903. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  1904. validate(&shader);
  1905. }
  1906. /// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float).
  1907. fn texcoord_mode(shader: &HostShader) -> u8 {
  1908. let c = Container::parse(&shader.dxil).unwrap();
  1909. let psv = c.part(FourCC::PSV0).unwrap().data;
  1910. let row = [1, 0, 0x44, 0, 3];
  1911. let at = psv.windows(5).position(|w| w == row).unwrap();
  1912. psv[at + 5]
  1913. }
  1914. const S_ENDPGM: u32 = 0xBF81_0000;
  1915. /// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads
  1916. /// the attribute's vertices: TEXCOORD0 becomes constant, read with
  1917. /// `attributeAtVertex`; i and j are `SV_Barycentrics` values.
  1918. #[test]
  1919. fn computed_barycentrics_read_the_vertices() {
  1920. let [e0, e1] = exp_mrt0(2);
  1921. let words = [
  1922. 0x1006_00F0, // v_mul_f32 v3, 0.5, v0
  1923. 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
  1924. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1925. e0,
  1926. e1,
  1927. S_ENDPGM,
  1928. ];
  1929. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1930. let (features, inputs) = parts(&shader);
  1931. assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
  1932. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  1933. assert_eq!(texcoord_mode(&shader), 1);
  1934. validate(&shader);
  1935. }
  1936. /// Weights from constants alone: the vertices, no `SV_Barycentrics`.
  1937. #[test]
  1938. fn constant_weights_need_no_barycentrics() {
  1939. let [e0, e1] = exp_mrt0(2);
  1940. let words = [
  1941. 0x7E06_02F0, // v_mov_b32 v3, 0.5
  1942. 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
  1943. 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
  1944. e0,
  1945. e1,
  1946. S_ENDPGM,
  1947. ];
  1948. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1949. let (features, inputs) = parts(&shader);
  1950. assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
  1951. assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
  1952. assert_eq!(texcoord_mode(&shader), 1);
  1953. validate(&shader);
  1954. }
  1955. /// The same attribute interpolated with the loaded i and j and with a
  1956. /// computed j: both from its vertices, the first weighed with
  1957. /// `SV_Barycentrics`.
  1958. #[test]
  1959. fn computed_and_loaded_barycentrics_on_one_attribute() {
  1960. let [e0, e1] = exp_mrt0(2);
  1961. let words = [
  1962. 0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y
  1963. 0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y
  1964. 0x1006_02F0, // v_mul_f32 v3, 0.5, v1
  1965. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  1966. 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
  1967. v_add_f32(2, 2, 4),
  1968. e0,
  1969. e1,
  1970. S_ENDPGM,
  1971. ];
  1972. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1973. let (_, inputs) = parts(&shader);
  1974. assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
  1975. assert_eq!(texcoord_mode(&shader), 1);
  1976. validate(&shader);
  1977. }
  1978. /// P10 of an attribute the program interpolates is P1 - P0.
  1979. #[test]
  1980. fn p10_of_an_interpolated_attribute() {
  1981. let [e0, e1] = exp_mrt0(2);
  1982. let words = [
  1983. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  1984. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  1985. 0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x
  1986. v_add_f32(2, 2, 4),
  1987. e0,
  1988. e1,
  1989. S_ENDPGM,
  1990. ];
  1991. let shader = pixel(&words, PERSP_CENTER).unwrap();
  1992. assert_eq!(texcoord_mode(&shader), 1);
  1993. validate(&shader);
  1994. // Alone, what the hardware holds is not known.
  1995. let [e0, e1] = exp_mrt0(4);
  1996. let words = [0xC812_0000, e0, e1, S_ENDPGM];
  1997. assert!(pixel(&words, PERSP_CENTER).is_err());
  1998. }
  1999. }