shader.rs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. //! A DXIL vertex, pixel, compute or mesh shader under construction: the module,
  2. //! the `dx.op` declarations it calls, its signatures and bound resources,
  3. //! and the metadata and container that wrap it up (SM 6.6, validator 1.6).
  4. use super::bitcode::{Attr, Md, Module, Ty, V};
  5. use super::container::{self, Binding, Psv, SigElement};
  6. /// Where the shader reads its user data: `b0` in this space.
  7. pub const USER_DATA_SPACE: u32 = 0;
  8. /// Where immediate samplers are bound: `s<n>` in this space.
  9. pub const SAMPLER_SPACE: u32 = 0;
  10. /// Where root CBVs and SRVs are bound: `b<root parameter index>` and
  11. /// `t<root parameter index>` in this space.
  12. pub const ROOT_CBV_SPACE: u32 = 1;
  13. /// The root SRV `t<SLOT_STRIDES>` in [`ROOT_CBV_SPACE`] of a shader that
  14. /// reads buffers through descriptors it picks from the view heap at an
  15. /// index it computes (SM 6.6 dynamic resources): a raw buffer of
  16. /// [`SLOT_STRIDES_COUNT`] dwords the host keeps, dword `i` the bytes per
  17. /// element of the buffer view at heap slot `i` (0: none or not a buffer).
  18. /// The console's descriptor holds that stride and its hardware multiplies
  19. /// the element index by it; the program's code does not say it, and the
  20. /// used-resource list only names what tables hold. A shader that has this
  21. /// root SRV also tells the host that the buffer views of the whole heap
  22. /// must be ready when it runs, not only those its tables name.
  23. pub const SLOT_STRIDES: u8 = 255;
  24. /// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it.
  25. pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
  26. /// Title memory by address (`resource::MEMORY`): console code reads and
  27. /// writes through raw 40-bit addresses it takes from root constants,
  28. /// descriptors and other memory (the ray-tracing structure builder and the
  29. /// programs that walk its structures). The host keeps copies of the title
  30. /// memory shaders use; a shader with such an access finds the copy by the
  31. /// address:
  32. ///
  33. /// - the root SRV `t<SLOT_MEMORY>` in [`ROOT_CBV_SPACE`] is a directory of
  34. /// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title
  35. /// address space: the number of the host copy holding that page (0: none
  36. /// yet) and the page's byte offset in that copy;
  37. /// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base`
  38. /// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself
  39. /// reads zeros and drops writes;
  40. /// - the root UAV `u<SLOT_FAULTS>` takes the page numbers of accesses that
  41. /// found no copy ([`MEMORY_FAULTS`] dwords, dword 0 a sink), which the
  42. /// host reads afterwards to make those copies for the frames to come.
  43. pub const SLOT_MEMORY: u8 = 254;
  44. /// See [`SLOT_MEMORY`].
  45. pub const SLOT_FAULTS: u8 = 253;
  46. /// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB.
  47. pub const MEMORY_PAGES: u32 = 1 << 21;
  48. /// Dwords of the [`SLOT_FAULTS`] buffer.
  49. pub const MEMORY_FAULTS: u32 = 4096;
  50. /// `RootType::Other` code of a user-data dword the host computes: the view
  51. /// heap slot of the memory copies' views ([`SLOT_MEMORY`]).
  52. pub const USER_MEMORY_BASE: u32 = 0x100;
  53. /// `RootType::Other` code of a user-data dword the host computes: the low
  54. /// 32 bits of the title address of the buffer view at dword `dword` of the
  55. /// descriptor table of root parameter `slot`; [`USER_VIEW_ADDRESS`] + 1:
  56. /// its bits from 32 up. (Console code reads the address out of a buffer
  57. /// descriptor and uses it as a pointer.)
  58. pub const USER_VIEW_ADDRESS: u32 = 0x101;
  59. /// `RootType::Other` code of a user-data dword the host computes: the
  60. /// bytes (0 to 15) by which the raw view the host binds for the root view
  61. /// of root parameter `slot` begins before the title's address. A raw view
  62. /// begins on 16 bytes of its host buffer; the console's root views begin
  63. /// anywhere (the structure builder's counters sit at addresses ending in
  64. /// 4 and c). The shader adds the dword to every byte offset through that
  65. /// view. Asked for every root UAV, and for the root SRVs of programs with
  66. /// a spilled user-data table.
  67. pub const USER_VIEW_BIAS: u32 = 0x103;
  68. /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
  69. pub(crate) mod flags {
  70. pub const RAW_BUFFERS: u64 = 1 << 4;
  71. pub const DOUBLES: u64 = 1 << 2;
  72. pub const STENCIL_REF: u64 = 1 << 11;
  73. pub const TYPED_UAV_LOADS: u64 = 1 << 13;
  74. pub const ROVS: u64 = 1 << 18;
  75. pub const WAVE_OPS: u64 = 1 << 19;
  76. pub const BARYCENTRICS: u64 = 1 << 22;
  77. pub const INT64: u64 = 1 << 20;
  78. pub const ATOMIC_TYPED64: u64 = 1 << 27;
  79. pub const ATOMIC_HEAP64: u64 = 1 << 32;
  80. pub const RESOURCE_HEAP: u64 = 1 << 30;
  81. pub const SAMPLER_HEAP: u64 = 1 << 31;
  82. }
  83. pub(crate) struct Types {
  84. pub void: Ty,
  85. pub i1: Ty,
  86. pub i32: Ty,
  87. pub f32: Ty,
  88. pub handle: Ty,
  89. pub props: Ty,
  90. pub bind: Ty,
  91. pub cbuf_ret: Ty,
  92. pub res_ret: Ty,
  93. }
  94. /// What a mesh shader declares beyond its thread-group size.
  95. #[derive(Debug, Clone, Copy)]
  96. pub(crate) struct Mesh {
  97. pub max_vertices: u32,
  98. pub max_primitives: u32,
  99. /// 1 lines, 2 triangles.
  100. pub topology: u8,
  101. }
  102. /// What a geometry shader declares: triangles in, triangle strips out on
  103. /// stream 0, one instance.
  104. #[derive(Debug, Clone, Copy)]
  105. pub(crate) struct Geometry {
  106. pub max_vertices: u32,
  107. }
  108. /// The null slot every host view heap keeps at its end (0: no limit). Shaders translated while
  109. /// it is set read that slot for any view index at or past it. A read past a heap's end is
  110. /// undefined: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is
  111. /// larger) hung its GPU (GPU-based validation: "descriptor heap index out of bounds"), and AMD
  112. /// RDNA3 took a page fault and removed the device.
  113. static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  114. /// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null.
  115. pub fn set_view_heap_limit(null_slot: u32) {
  116. VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed);
  117. }
  118. /// See [`VIEW_LIMIT`]: the null slot shaders translated now clamp view indices to (0: none).
  119. pub fn view_heap_limit() -> u32 {
  120. VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed)
  121. }
  122. pub(crate) struct Shader {
  123. pub m: Module,
  124. pub t: Types,
  125. pub pixel: bool,
  126. pub inputs: Vec<SigElement>,
  127. pub outputs: Vec<SigElement>,
  128. /// A mesh shader's per-primitive outputs.
  129. pub prims: Vec<SigElement>,
  130. /// A mesh shader (`threads` is its thread-group size).
  131. pub mesh: Option<Mesh>,
  132. /// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false.
  133. pub geometry: Option<Geometry>,
  134. /// Dwords of user data the shader reads (0: no user-data buffer).
  135. pub user_data: u32,
  136. /// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`].
  137. pub samplers: u32,
  138. /// Bit n: immediate sampler n is a comparison sampler.
  139. pub cmp_samplers: u64,
  140. /// Root CBVs read, by root parameter index, with their handles.
  141. pub root_cbvs: Vec<(u8, V)>,
  142. /// Root SRVs (raw buffers) read, likewise.
  143. pub root_srvs: Vec<(u8, V)>,
  144. /// Root UAVs (raw buffers) read or written, likewise.
  145. pub root_uavs: Vec<(u8, V)>,
  146. pub flags: u64,
  147. /// Heap handles made with a non-uniform index.
  148. pub nonuniform_handles: u32,
  149. /// A compute shader with this thread-group size.
  150. pub threads: Option<[u32; 3]>,
  151. /// The wave size a compute shader requires (`WaveSize`).
  152. pub wave_size: Option<u32>,
  153. /// Thread-group shared memory, in dwords.
  154. pub lds_dwords: u32,
  155. lds: Option<V>,
  156. main: V,
  157. pub entry: usize,
  158. }
  159. impl Shader {
  160. pub fn new(pixel: bool) -> Self {
  161. let mut m = Module::default();
  162. let void = m.void();
  163. let i1 = m.int(1);
  164. let i8 = m.int(8);
  165. let i32 = m.int(32);
  166. let f32 = m.float();
  167. let i8p = m.ptr(i8);
  168. let handle = m.named_struct("dx.types.Handle", vec![i8p]);
  169. let props = m.named_struct("dx.types.ResourceProperties", vec![i32, i32]);
  170. let bind = m.named_struct("dx.types.ResBind", vec![i32, i32, i32, i8]);
  171. let cbuf_ret = m.named_struct("dx.types.CBufRet.i32", vec![i32, i32, i32, i32]);
  172. let res_ret = m.named_struct("dx.types.ResRet.f32", vec![f32, f32, f32, f32, i32]);
  173. let main_ty = m.func_ty(void, vec![]);
  174. m.ptr(main_ty);
  175. let main = m.function("main", main_ty, None, true);
  176. let entry = m.new_block();
  177. Shader {
  178. m,
  179. t: Types {
  180. void,
  181. i1,
  182. i32,
  183. f32,
  184. handle,
  185. props,
  186. bind,
  187. cbuf_ret,
  188. res_ret,
  189. },
  190. pixel,
  191. inputs: Vec::new(),
  192. outputs: Vec::new(),
  193. prims: Vec::new(),
  194. mesh: None,
  195. geometry: None,
  196. user_data: 0,
  197. samplers: 0,
  198. cmp_samplers: 0,
  199. root_cbvs: Vec::new(),
  200. root_srvs: Vec::new(),
  201. root_uavs: Vec::new(),
  202. flags: 0,
  203. nonuniform_handles: 0,
  204. threads: None,
  205. wave_size: None,
  206. lds_dwords: 0,
  207. lds: None,
  208. main,
  209. entry,
  210. }
  211. }
  212. /// The thread-group shared memory: `[lds_dwords x i32]` in address
  213. /// space 3.
  214. pub fn lds(&mut self) -> V {
  215. if let Some(g) = self.lds {
  216. return g;
  217. }
  218. let arr = self.m.array(self.lds_dwords, self.t.i32);
  219. let g = self.m.global("lds", arr, 3);
  220. self.lds = Some(g);
  221. g
  222. }
  223. /// Calls `dx.op.<name>` (class and overload) with `opcode` and `args`.
  224. pub fn op(
  225. &mut self,
  226. block: usize,
  227. name: &str,
  228. attr: Attr,
  229. ret: Ty,
  230. opcode: u32,
  231. args: &[V],
  232. ) -> V {
  233. let mut params = vec![self.t.i32];
  234. params.extend(args.iter().map(|&a| self.m.type_of(a)));
  235. let fty = self.m.func_ty(ret, params);
  236. self.m.ptr(fty);
  237. let f = self
  238. .m
  239. .function(&format!("dx.op.{name}"), fty, Some(attr), false);
  240. let mut all = vec![self.m.i32(opcode)];
  241. all.extend(args);
  242. self.m.call(block, f, all)
  243. }
  244. /// The handle of the user-data constant buffer, made in the entry block.
  245. pub fn user_data_handle(&mut self) -> V {
  246. let bind = [
  247. self.m.i32(0),
  248. self.m.i32(0),
  249. self.m.i32(USER_DATA_SPACE),
  250. self.m.i8(2), // CBV
  251. ];
  252. let bind = self.m.aggregate(self.t.bind, &bind);
  253. let block = self.entry;
  254. let (i, f) = (self.m.i32(0), self.m.bool(false));
  255. let h = self.op(
  256. block,
  257. "createHandleFromBinding",
  258. Attr::ReadNone,
  259. self.t.handle,
  260. 217,
  261. &[bind, i, f],
  262. );
  263. // The size is known in `finish`, which fixes this placeholder.
  264. self.annotate(block, h, 13, u32::MAX)
  265. }
  266. /// The handle of the root CBV of root parameter `slot`, made in the
  267. /// entry block.
  268. pub fn root_cbv_handle(&mut self, slot: u8) -> V {
  269. if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) {
  270. return h;
  271. }
  272. let r = self.m.i32(u32::from(slot));
  273. let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)];
  274. let bind = self.m.aggregate(self.t.bind, &bind);
  275. let f = self.m.bool(false);
  276. let block = self.entry;
  277. let h = self.op(
  278. block,
  279. "createHandleFromBinding",
  280. Attr::ReadNone,
  281. self.t.handle,
  282. 217,
  283. &[bind, r, f],
  284. );
  285. let h = self.annotate(block, h, 13, 65536);
  286. self.root_cbvs.push((slot, h));
  287. h
  288. }
  289. /// The handle of the root SRV (a raw buffer) of root parameter `slot`.
  290. pub fn root_srv_handle(&mut self, slot: u8) -> V {
  291. if let Some(&(_, h)) = self.root_srvs.iter().find(|r| r.0 == slot) {
  292. return h;
  293. }
  294. let r = self.m.i32(u32::from(slot));
  295. let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(0)];
  296. let bind = self.m.aggregate(self.t.bind, &bind);
  297. let f = self.m.bool(false);
  298. let block = self.entry;
  299. let h = self.op(
  300. block,
  301. "createHandleFromBinding",
  302. Attr::ReadNone,
  303. self.t.handle,
  304. 217,
  305. &[bind, r, f],
  306. );
  307. let h = self.annotate(block, h, 11, 0);
  308. self.flags |= flags::RAW_BUFFERS;
  309. self.root_srvs.push((slot, h));
  310. h
  311. }
  312. /// The handle of the root UAV (a raw buffer) of root parameter `slot`:
  313. /// `u<slot>` in [`ROOT_CBV_SPACE`].
  314. pub fn root_uav_handle(&mut self, slot: u8) -> V {
  315. if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) {
  316. return h;
  317. }
  318. let r = self.m.i32(u32::from(slot));
  319. let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)];
  320. let bind = self.m.aggregate(self.t.bind, &bind);
  321. let f = self.m.bool(false);
  322. let block = self.entry;
  323. let h = self.op(
  324. block,
  325. "createHandleFromBinding",
  326. Attr::ReadNone,
  327. self.t.handle,
  328. 217,
  329. &[bind, r, f],
  330. );
  331. let h = self.annotate(block, h, 11 | 0x1000, 0);
  332. self.flags |= flags::RAW_BUFFERS;
  333. self.root_uavs.push((slot, h));
  334. h
  335. }
  336. /// The handle of immediate sampler `n` (a comparison sampler when its
  337. /// bit in `cmp_samplers` is set).
  338. pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
  339. let bind = [
  340. self.m.i32(n),
  341. self.m.i32(n),
  342. self.m.i32(SAMPLER_SPACE),
  343. self.m.i8(3), // sampler
  344. ];
  345. let bind = self.m.aggregate(self.t.bind, &bind);
  346. let (i, f) = (self.m.i32(n), self.m.bool(false));
  347. let h = self.op(
  348. block,
  349. "createHandleFromBinding",
  350. Attr::ReadNone,
  351. self.t.handle,
  352. 217,
  353. &[bind, i, f],
  354. );
  355. let cmp = if self.cmp_samplers >> n & 1 != 0 {
  356. 0x8000
  357. } else {
  358. 0
  359. };
  360. self.annotate(block, h, 14 | cmp, 0)
  361. }
  362. pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V {
  363. let p = [self.m.i32(props0), self.m.i32(props1)];
  364. let p = self.m.aggregate(self.t.props, &p);
  365. self.op(
  366. block,
  367. "annotateHandle",
  368. Attr::ReadNone,
  369. self.t.handle,
  370. 216,
  371. &[h, p],
  372. )
  373. }
  374. /// A descriptor heap handle, annotated with `props`; `nonuniform` when
  375. /// the index may differ between lanes (`NonUniformResourceIndex`).
  376. pub fn heap_handle(
  377. &mut self,
  378. block: usize,
  379. index: V,
  380. sampler: bool,
  381. nonuniform: bool,
  382. props: (u32, u32),
  383. ) -> V {
  384. // a view index past the host heap (`set_view_heap_limit`) reads its null slot instead
  385. let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed);
  386. // (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid)
  387. let index = if !sampler && limit != 0 {
  388. let null = self.m.i32(limit);
  389. let i32t = self.t.i32;
  390. let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]);
  391. self.m.tag(v, super::bitcode::Tag::Clamp);
  392. v
  393. } else if sampler {
  394. // A sampler heap has at most 2,048 samplers on any host: an
  395. // index past that (a number read from memory the host has not
  396. // got yet) stays inside the largest heap there is.
  397. // shortcut: not the bound heap's own count, which a title
  398. // heap smaller than 2,048 would need.
  399. let last = self.m.i32(2047);
  400. let i32t = self.t.i32;
  401. let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]);
  402. self.m.tag(v, super::bitcode::Tag::Clamp);
  403. v
  404. } else {
  405. index
  406. };
  407. self.flags |= if sampler {
  408. flags::SAMPLER_HEAP
  409. } else {
  410. flags::RESOURCE_HEAP
  411. };
  412. self.nonuniform_handles += u32::from(nonuniform);
  413. let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform));
  414. let h = self.op(
  415. block,
  416. "createHandleFromHeap",
  417. Attr::ReadNone,
  418. self.t.handle,
  419. 218,
  420. &[index, s, n],
  421. );
  422. self.annotate(block, h, props.0, props.1)
  423. }
  424. /// The finished container.
  425. pub fn finish(mut self) -> Vec<u8> {
  426. let ud_size = (self.user_data * 4).next_multiple_of(16);
  427. self.fix_user_data_size(ud_size);
  428. // The clean-up, before anything is declared about the code: a
  429. // feature whose last use it removed must not be declared (the
  430. // validator compares the flags with what the code uses).
  431. let passes = super::shader_opt() & super::bitcode::opt::MODULE;
  432. if passes != 0 {
  433. self.m.optimise(passes);
  434. let used = self.m.usage();
  435. for (flag, used) in [
  436. (flags::ROVS, used.rovs),
  437. (flags::WAVE_OPS, used.wave_ops),
  438. (flags::INT64, used.int64),
  439. (flags::TYPED_UAV_LOADS, used.typed_uav_loads),
  440. (flags::RESOURCE_HEAP, used.heap_views),
  441. (flags::SAMPLER_HEAP, used.heap_samplers),
  442. (flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64, used.atomic64),
  443. ] {
  444. if !used {
  445. self.flags &= !flag;
  446. }
  447. }
  448. }
  449. let mut resources = None;
  450. let mut bindings = Vec::new();
  451. let i32c = |s: &mut Self, v: u32| {
  452. let c = s.m.i32(v);
  453. s.m.md_value(c)
  454. };
  455. if self.user_data > 0
  456. || self.samplers > 0
  457. || !self.root_cbvs.is_empty()
  458. || !self.root_srvs.is_empty()
  459. || !self.root_uavs.is_empty()
  460. {
  461. let empty = self.m.md_str("");
  462. let mut cbvs = None;
  463. let mut cbv_list = Vec::new();
  464. if self.user_data > 0 {
  465. let arr = self.m.array(self.user_data.next_multiple_of(4), self.t.i32);
  466. let ty = self.m.named_struct("UserData", vec![arr]);
  467. let p = self.m.ptr(ty);
  468. let u = self.m.undef(p);
  469. let ops = vec![
  470. Some(i32c(&mut self, 0)),
  471. Some(self.m.md_value(u)),
  472. Some(empty),
  473. Some(i32c(&mut self, USER_DATA_SPACE)),
  474. Some(i32c(&mut self, 0)),
  475. Some(i32c(&mut self, 1)),
  476. Some(i32c(&mut self, ud_size)),
  477. None,
  478. ];
  479. cbv_list.push(Some(self.m.md_node(ops)));
  480. bindings.push(Binding {
  481. kind: 2,
  482. space: USER_DATA_SPACE,
  483. register: 0,
  484. dxil_kind: 13,
  485. });
  486. }
  487. let blob = self.m.array(16384, self.t.i32);
  488. let ty = self.m.named_struct("RootCbv", vec![blob]);
  489. let p = self.m.ptr(ty);
  490. let u = self.m.undef(p);
  491. for (slot, _) in self.root_cbvs.clone() {
  492. let ops = vec![
  493. Some(i32c(&mut self, cbv_list.len() as u32)),
  494. Some(self.m.md_value(u)),
  495. Some(empty),
  496. Some(i32c(&mut self, ROOT_CBV_SPACE)),
  497. Some(i32c(&mut self, u32::from(slot))),
  498. Some(i32c(&mut self, 1)),
  499. Some(i32c(&mut self, 65536)),
  500. None,
  501. ];
  502. cbv_list.push(Some(self.m.md_node(ops)));
  503. bindings.push(Binding {
  504. kind: 2,
  505. space: ROOT_CBV_SPACE,
  506. register: u32::from(slot),
  507. dxil_kind: 13,
  508. });
  509. }
  510. if !cbv_list.is_empty() {
  511. cbvs = Some(self.m.md_node(cbv_list));
  512. }
  513. let mut srvs = None;
  514. if !self.root_srvs.is_empty() {
  515. let ty = self
  516. .m
  517. .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]);
  518. let p = self.m.ptr(ty);
  519. let u = self.m.undef(p);
  520. let mut list = Vec::new();
  521. for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() {
  522. let ops = vec![
  523. Some(i32c(&mut self, n as u32)),
  524. Some(self.m.md_value(u)),
  525. Some(empty),
  526. Some(i32c(&mut self, ROOT_CBV_SPACE)),
  527. Some(i32c(&mut self, u32::from(slot))),
  528. Some(i32c(&mut self, 1)),
  529. Some(i32c(&mut self, 11)),
  530. Some(i32c(&mut self, 0)),
  531. None,
  532. ];
  533. list.push(Some(self.m.md_node(ops)));
  534. bindings.push(Binding {
  535. kind: 4,
  536. space: ROOT_CBV_SPACE,
  537. register: u32::from(slot),
  538. dxil_kind: 11,
  539. });
  540. }
  541. srvs = Some(self.m.md_node(list));
  542. }
  543. let mut uavs = None;
  544. if !self.root_uavs.is_empty() {
  545. let ty = self
  546. .m
  547. .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]);
  548. let p = self.m.ptr(ty);
  549. let u = self.m.undef(p);
  550. let no = self.m.bool(false);
  551. let no = self.m.md_value(no);
  552. let mut list = Vec::new();
  553. for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() {
  554. // Id, variable, name, space, lower bound, range size,
  555. // shape (11: raw buffer), globally coherent, counter,
  556. // rasterizer ordered, no extra properties.
  557. let ops = vec![
  558. Some(i32c(&mut self, n as u32)),
  559. Some(self.m.md_value(u)),
  560. Some(empty),
  561. Some(i32c(&mut self, ROOT_CBV_SPACE)),
  562. Some(i32c(&mut self, u32::from(slot))),
  563. Some(i32c(&mut self, 1)),
  564. Some(i32c(&mut self, 11)),
  565. Some(no),
  566. Some(no),
  567. Some(no),
  568. None,
  569. ];
  570. list.push(Some(self.m.md_node(ops)));
  571. bindings.push(Binding {
  572. kind: 7,
  573. space: ROOT_CBV_SPACE,
  574. register: u32::from(slot),
  575. dxil_kind: 11,
  576. });
  577. }
  578. uavs = Some(self.m.md_node(list));
  579. }
  580. let mut samplers = None;
  581. if self.samplers > 0 {
  582. let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]);
  583. let p = self.m.ptr(ty);
  584. let u = self.m.undef(p);
  585. let mut list = Vec::new();
  586. for n in 0..self.samplers {
  587. let kind = (self.cmp_samplers >> n & 1) as u32;
  588. let ops = vec![
  589. Some(i32c(&mut self, n)),
  590. Some(self.m.md_value(u)),
  591. Some(empty),
  592. Some(i32c(&mut self, SAMPLER_SPACE)),
  593. Some(i32c(&mut self, n)),
  594. Some(i32c(&mut self, 1)),
  595. // Sampler kind: 1 comparison.
  596. Some(i32c(&mut self, kind)),
  597. None,
  598. ];
  599. list.push(Some(self.m.md_node(ops)));
  600. bindings.push(Binding {
  601. kind: 1,
  602. space: SAMPLER_SPACE,
  603. register: n,
  604. dxil_kind: 14,
  605. });
  606. }
  607. samplers = Some(self.m.md_node(list));
  608. }
  609. resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers]));
  610. // PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs.
  611. bindings.sort_by_key(|b| match b.kind {
  612. 2 => 0,
  613. 1 => 1,
  614. 7 => 3,
  615. _ => 2,
  616. });
  617. }
  618. if let Some(r) = resources {
  619. self.m.named_md("dx.resources", vec![r]);
  620. }
  621. let graphics = self.threads.is_none() || self.mesh.is_some();
  622. if graphics {
  623. // shortcut: every output is declared to depend on every input; the
  624. // exact sets need a dependence pass. Drivers read this state.
  625. let scalars = |els: &[SigElement]| {
  626. els.iter()
  627. .filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
  628. .max()
  629. .unwrap_or(0)
  630. };
  631. let (ni, no) = (scalars(&self.inputs), scalars(&self.outputs));
  632. let mut view = vec![ni, no];
  633. // Mesh shaders have no inputs: then the primitive outputs' count.
  634. if self.mesh.is_some() {
  635. view.push(scalars(&self.prims));
  636. }
  637. for _ in 0..ni {
  638. for k in 0..no.div_ceil(32) {
  639. let bits = (no - 32 * k).min(32);
  640. view.push(if bits == 32 {
  641. u32::MAX
  642. } else {
  643. (1 << bits) - 1
  644. });
  645. }
  646. }
  647. // A geometry shader lists four streams: the other three have
  648. // no outputs.
  649. if self.geometry.is_some() {
  650. view.extend([0, 0, 0]);
  651. }
  652. let arr = self.m.array(view.len() as u32, self.t.i32);
  653. let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect();
  654. let arr = self.m.aggregate(arr, &elems);
  655. let arr = self.m.md_value(arr);
  656. let view_node = self.m.md_node(vec![Some(arr)]);
  657. self.m.named_md("dx.viewIdState", vec![view_node]);
  658. }
  659. let sigs = if graphics {
  660. let ins = self.signature_md(self.inputs.clone());
  661. let outs = self.signature_md(self.outputs.clone());
  662. let prims = self.signature_md(self.prims.clone());
  663. Some(self.m.md_node(vec![ins, outs, prims]))
  664. } else {
  665. None
  666. };
  667. // A pixel shader with an SV_StencilRef output (as DXC collects it).
  668. if self.pixel && self.outputs.iter().any(|o| o.kind == 20) {
  669. self.flags |= flags::STENCIL_REF;
  670. }
  671. // Entry properties: shader flags (tag 0), geometry state (1),
  672. // thread-group size (4), wave size (11).
  673. let mut props = Vec::new();
  674. if self.flags != 0 {
  675. props.push(i32c(&mut self, 0));
  676. let i64t = self.m.int(64);
  677. let f = self.m.int_const(i64t, self.flags as i64);
  678. props.push(self.m.md_value(f));
  679. }
  680. if let Some(g) = self.geometry {
  681. // Input primitive (3: triangles), maximum vertices, stream
  682. // mask, output topology (5: triangle strips), instances.
  683. props.push(i32c(&mut self, 1));
  684. let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n)));
  685. props.push(self.m.md_node(state.to_vec()));
  686. }
  687. if let Some(threads) = self.threads {
  688. let t = threads.map(|n| Some(i32c(&mut self, n)));
  689. let t = self.m.md_node(t.to_vec());
  690. match self.mesh {
  691. // Mesh state (tag 9): threads, maximum vertices and
  692. // primitives, topology, payload bytes.
  693. Some(mesh) => {
  694. props.push(i32c(&mut self, 9));
  695. let state = [
  696. mesh.max_vertices,
  697. mesh.max_primitives,
  698. mesh.topology.into(),
  699. 0,
  700. ]
  701. .map(|n| Some(i32c(&mut self, n)));
  702. let mut node = vec![Some(t)];
  703. node.extend(state);
  704. props.push(self.m.md_node(node));
  705. }
  706. None => {
  707. props.push(i32c(&mut self, 4));
  708. props.push(t);
  709. }
  710. }
  711. }
  712. if let Some(n) = self.wave_size {
  713. props.push(i32c(&mut self, 11));
  714. let n = Some(i32c(&mut self, n));
  715. props.push(self.m.md_node(vec![n]));
  716. }
  717. let props =
  718. (!props.is_empty()).then(|| self.m.md_node(props.into_iter().map(Some).collect()));
  719. let main = self.m.md_value(self.main);
  720. let name = self.m.md_str("main");
  721. let entry = self
  722. .m
  723. .md_node(vec![Some(main), Some(name), sigs, resources, props]);
  724. let ident = self.m.md_str("victory");
  725. let ident = self.m.md_node(vec![Some(ident)]);
  726. self.m.named_md("llvm.ident", vec![ident]);
  727. let one = i32c(&mut self, 1);
  728. let six = i32c(&mut self, 6);
  729. let version = self.m.md_node(vec![Some(one), Some(six)]);
  730. self.m.named_md("dx.version", vec![version]);
  731. self.m.named_md("dx.valver", vec![version]);
  732. // Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh.
  733. let (name, kind) = match (self.threads, self.pixel) {
  734. _ if self.mesh.is_some() => ("ms", 13u32),
  735. _ if self.geometry.is_some() => ("gs", 2),
  736. (Some(_), _) => ("cs", 5u32),
  737. (None, true) => ("ps", 0),
  738. (None, false) => ("vs", 1),
  739. };
  740. let name = self.m.md_str(name);
  741. let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]);
  742. self.m.named_md("dx.shaderModel", vec![sm]);
  743. self.m.named_md("dx.entryPoints", vec![entry]);
  744. let bitcode = self.m.write();
  745. super::bitcode::census::note(&self.m, &bitcode);
  746. let mut dxil = Vec::with_capacity(24 + bitcode.len());
  747. dxil.extend((kind << 16 | 0x66).to_le_bytes());
  748. dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes());
  749. dxil.extend(b"DXIL");
  750. dxil.extend(0x106u32.to_le_bytes());
  751. dxil.extend(16u32.to_le_bytes());
  752. dxil.extend((bitcode.len() as u32).to_le_bytes());
  753. dxil.extend(&bitcode);
  754. let mut features = 0u64;
  755. if self.flags & flags::DOUBLES != 0 {
  756. features |= 0x1;
  757. }
  758. if self.flags & flags::STENCIL_REF != 0 {
  759. features |= 0x200;
  760. }
  761. if self.flags & flags::TYPED_UAV_LOADS != 0 {
  762. features |= 0x800;
  763. }
  764. if self.flags & flags::ROVS != 0 {
  765. features |= 0x1000;
  766. }
  767. if self.flags & flags::WAVE_OPS != 0 {
  768. features |= 0x4000;
  769. }
  770. if self.flags & flags::INT64 != 0 {
  771. features |= 0x8000;
  772. }
  773. if self.flags & flags::BARYCENTRICS != 0 {
  774. features |= 0x2_0000;
  775. }
  776. if self.flags & flags::RESOURCE_HEAP != 0 {
  777. features |= 0x200_0000;
  778. }
  779. if self.flags & flags::SAMPLER_HEAP != 0 {
  780. features |= 0x400_0000;
  781. }
  782. if self.flags & flags::ATOMIC_TYPED64 != 0 {
  783. features |= 0x40_0000;
  784. }
  785. if self.flags & flags::ATOMIC_HEAP64 != 0 {
  786. features |= 0x1000_0000;
  787. }
  788. let sfi0 = features.to_le_bytes();
  789. let isg1 = container::signature(&self.inputs, true);
  790. let osg1 = container::signature(&self.outputs, false);
  791. let flag = if self.pixel {
  792. self.outputs.iter().any(|o| (17..=19).contains(&o.kind))
  793. } else {
  794. self.outputs.iter().any(|o| o.kind == 3)
  795. };
  796. let psv0 = container::psv(&Psv {
  797. stage: kind as u8,
  798. flag: flag && self.threads.is_none(),
  799. inputs: &self.inputs,
  800. outputs: &self.outputs,
  801. prims: &self.prims,
  802. mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)),
  803. geometry: self.geometry.map(|g| g.max_vertices),
  804. bindings: &bindings,
  805. threads: self.threads.unwrap_or_default(),
  806. wave_size: self.wave_size,
  807. });
  808. let hash = [0u8; 20];
  809. let psg1 = container::signature(&self.prims, false);
  810. let mut parts: Vec<(&[u8; 4], &[u8])> =
  811. vec![(b"SFI0", &sfi0), (b"ISG1", &isg1), (b"OSG1", &osg1)];
  812. if self.mesh.is_some() {
  813. parts.push((b"PSG1", &psg1));
  814. }
  815. parts.extend([(b"PSV0", &psv0[..]), (b"HASH", &hash), (b"DXIL", &dxil)]);
  816. container::build(&parts)
  817. }
  818. /// The user-data buffer's annotation carries its size, known only now.
  819. fn fix_user_data_size(&mut self, size: u32) {
  820. let old = [self.m.i32(13), self.m.i32(u32::MAX)];
  821. let old = self.m.aggregate(self.t.props, &old);
  822. let new = [self.m.i32(13), self.m.i32(size)];
  823. let new = self.m.aggregate(self.t.props, &new);
  824. self.m.replace_const(old, new);
  825. }
  826. fn signature_md(&mut self, elements: Vec<SigElement>) -> Option<Md> {
  827. if elements.is_empty() {
  828. return None;
  829. }
  830. let mut list = Vec::new();
  831. for (id, e) in elements.iter().enumerate() {
  832. let c32 = |s: &mut Self, v: u32| {
  833. let c = s.m.i32(v);
  834. Some(s.m.md_value(c))
  835. };
  836. let c8 = |s: &mut Self, v: u8| {
  837. let c = s.m.i8(v);
  838. Some(s.m.md_value(c))
  839. };
  840. let idx = c32(self, e.index);
  841. let indices = Some(self.m.md_node(vec![idx]));
  842. let usage = if e.usage != 0 {
  843. let (tag, mask) = (c32(self, 3), c32(self, u32::from(e.usage)));
  844. Some(self.m.md_node(vec![tag, mask]))
  845. } else {
  846. None
  847. };
  848. let ops = vec![
  849. c32(self, id as u32),
  850. Some(self.m.md_str(&e.name)),
  851. c8(self, e.comp),
  852. c8(self, e.kind),
  853. indices,
  854. c8(self, e.interp),
  855. c32(self, 1),
  856. c8(self, e.cols),
  857. c32(self, e.row.unwrap_or(u32::MAX)),
  858. c8(self, if e.row.is_some() { e.col } else { u8::MAX }),
  859. usage,
  860. ];
  861. list.push(Some(self.m.md_node(ops)));
  862. }
  863. Some(self.m.md_node(list))
  864. }
  865. }